Centering images in a div vertically

我与影子孤独终老i 提交于 2019-12-02 18:21:08

问题


I have this code for centering vertically the images in a bunch of divs.

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");

.. but it doesn't seem to work.


回答1:


Try this instead...

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);
});

You weren't actually passing in images, just the class selector. The above selects all relevant images and passes them in - there's no need for the parent parameter.




回答2:


Try to this one,

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



回答3:


if your div have all the same height and contain only the image, that's a pure CSS solution:
http://jsfiddle.net/Tpy2w/

Relevant CSS

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

div img {
  vertical-align: middle;
}

Just set an height and the same line-height for the div. Then apply vertical-align: middle on the image



来源:https://stackoverflow.com/questions/11757229/centering-images-in-a-div-vertically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!