简体   繁体   English

使用jQuery在div中垂直居中

[英]Vertically centering image in a div using jQuery

Hoping someone can point me in the right direction. 希望有人可以指出正确的方向。

I've been trying to vertically center an image within a div, which I can do using CSS IF the height of the image is consistent. 我一直在尝试在div内垂直居中放置图像,如果图像的高度一致,则可以使用CSS进行。 However (as always) things aren't as simple as that and the image height is different in pretty much every instance. 但是(一如既往)事情并没有那么简单,并且几乎每个实例中的图像高度都不同。

I'd like to be able to add a negative margin of half the image height, to the image, to pull it into the center of the div. 我希望能够为图像添加一半图像高度的负边距,以将其拉到div的中心。

Any suggestions in how I do that? 我对此有何建议?

This doesn't seem to be working :S 这似乎不起作用:S

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

Thanks in advance. 提前致谢。

This code was found on SO some time ago. 这段代码是在SO上找到的。 You use it like this 你这样用

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

It calculates height of the parent element and centers it accordingly. 它计算父元素的高度并相应地居中。

Function: 功能:

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

Yo do not need jQuery for it, CSS could do it. 哟不需要jQuery,CSS可以做到。 Just set your image to be: 只需将您的图像设置为:

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

Also if you wonder for a hack to support inline-block on IE7 there you have: http://www.kollerat.com/cms/index.php/Web-admin/HTML/IE7-and-inline-block.html 另外,如果您想寻找一种在IE7上支持内联阻止的黑客,那么您也可以: http : //www.kollerat.com/cms/index.php/Web-admin/HTML/IE7-and-inline-block.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM