将图像垂直居中在div中 [英] Centering images in a div vertically

查看:149
本文介绍了将图像垂直居中在div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

试试这个......

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.

这篇关于将图像垂直居中在div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆