将图像垂直居中在div中

我有这个代码用于在一堆div中垂直居中图像。

function centerImages(parent, image) { var parent_height = $(image).parent().height(); var image_height = $(image).height(); var top_margin = (parent_height - image_height)/2; $(image).css( 'margin-top' , top_margin); } centerImages(".clients li", ".clients li img"); 

..但它似乎不起作用。

试试这个……

 function centerImages(image) { var parent_height = $(image).parent().height(); var image_height = $(image).height(); var top_margin = (parent_height - image_height) / 2; $(image).css( 'margin-top' , top_margin); } $(".clients li img").each(function() { centerImages(this); }); 

你实际上并没有传入图像,只是类选择器。 以上选择所有相关图像并传入它们 – 不需要父参数。

尝试这个,

 div.clients li img { vertical-align:middle; } 

如果您的div具有相同的高度并且仅包含图像,那么这是一个纯CSS解决方案:
http://jsfiddle.net/Tpy2w/

相关的CSS

 div { width: 300px; height : 300px; line-height: 300px; text-align: center; } div img { vertical-align: middle; } 

只需为div设置一个height和相同的line-height 。 然后在图像上应用vertical-align: middle