使用jQuery在div中垂直居中图像

时间:2012-07-17 17:08:34

标签: jquery getimagesize

希望有人能指出我正确的方向。

我一直试图在div中垂直居中图像,我可以使用CSS IF图像的高度是一致的。然而(一如既往)事情并不那么简单,图像高度几乎在每个实例中都不同。

我希望能够为图像添加图像高度的一半的负边距,将其拉入div的中心。

有关我如何做的任何建议?

这似乎不起作用:S

var $img = $('div#imageColumn img');
var h = $img.height();
$img.css('margin-top', + h / -2 + "px"); 

提前致谢。

2 个答案:

答案 0 :(得分:0)

此代码是在SO上发现的。你像这样使用它

$(".yourclass").vAlign();

它计算父元素的高度并相应地居中。

功能:

(function ($) {
    // VERTICALLY ALIGN FUNCTION
    $.fn.vAlign = function () {
        return this.each(function (i) {
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = Math.ceil((ph - ah) / 2);
            if (mh > 0) {
                $(this).css('margin-top', mh);
            } else {
                $(this).css('margin-top', 0);
            }
        });
    };
})(jQuery);

答案 1 :(得分:0)

哟不需要jQuery,CSS可以做到。只需将图像设置为:

.yourDiv .yourImg{
  display: inline-block;
  vertical-align: middle;
  /* if you wonder for a maximum height just add */
  max-height: 200px;   
}

另外如果你想知道在IE7上支持inline-block的hack,你有: http://www.kollerat.com/cms/index.php/Web-admin/HTML/IE7-and-inline-block.html