Centering images vertically
HTML:
<ul>
<li><img src="image1.png" /></li>
<li><img src="image2.png" /></li>开发者_开发问答;
<li><img src="image3.png" /></li>
<li><img src="image4.png" /></li>
<li><img src="image5.png" /></li>
<li><img src="image6.png" /></li>
</ul>
... the images are all different sizes, I'd like to center them vertically.
jQuery:
$('ul li').css('paddingTop', height($("ul li").height() - ("li img") / (2)));
# padding-top = height of li - height of image / 2
.. but this isn't working.
A Better Way?
If you're using jQuery, why not use one of the centering plugins?
// make sure li in this case is position:relative;
$("ul li img").center();
Present Problems
The following line has many problems:
height($("ul li").height() - ("li img") / (2))
height()
is not a function, unless you've declared it elsewhere. If so, what is it suppose to do exactly? Note, I'm not referring to $.height()
, which is a valid method in the jQuery Framework. Additionally, ("li img")
is not a numerical value, so dividing it by 2 makes no sense.
Perhaps the following may be more helpful:
$("ul li img").each(function(){
var pHeight = $(this).parent().height();
var iHeight = $(this).height();
var diff = Math.round(pHeight - iHeight);
$(this).parent().css("paddingTop", diff);
});
I think @Jonathan's answer is what you should follow ( centering plugin ) but here is your code cleaned up quite a bit:
$('ul li').each(function(){
var $li = $(this), $img = $li.find('img');
$img.css('padding-top', ($li.height() / 2) - ($img.height() / 2));
});
Of course, this will only work when the li
has a fixed height in the CSS.
Vertically center
$('ul li img').each(function(){
var height=$(this).outerHeight(),
li=$(this).closest('li'),
li_height=li.outerHeight();
li.height(li_height+'px');
$(this).css({marginTop: (li_height-height)/2+'px'});
});
精彩评论