使图像按比例填充div并垂直居中图像

时间:2013-06-13 10:00:12

标签: jquery css

如果之前有人使用过InDesign,当您将图像放在框架内时,右键单击框架将允许您选择按比例填充框选项,以便整个框架包含图像并且隐藏任何溢出,然后您可以中心内容

如何在浏览器中实现这种效果?

enter image description here

1 个答案:

答案 0 :(得分:5)

我创建了一个有助于实现此结果的fiddle

但是,如果div.frame宽度大于其图像宽度,则会导致图像扩展大于其分辨率。

假设以下HTML

<div class="frame">
    <img src="http://stuffpoint.com/parrots/image/240658-parrots-white-parrot.jpg" />
</div>

这将应用以下样式

.frame {
  width: 100%;
  height: 200px;
  overflow: hidden;
  position: relative;
}

.frame img {
  width: 100%;
}

强制jQuery在加载和调整大小时垂直居中图像

$(function(){
    centerImageVertically();
    $(window).resize(function() {
        centerImageVertically();
    });
    function centerImageVertically() {
        var imgframes = $('.frame img');
        imgframes.each(function(i){
            var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
            $(this).css({
                'position': 'absolute',
                'top': imgVRelativeOffset * -1
            });
        });
    }
});

更新:构建上述JavaScript的另一种方法:

    $(function () {
        var centerImageVertically = function () {
            var imgframes = $('.frame img');
            imgframes.each(function (i) {
                var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
                $(this).css({
                    'position': 'absolute',
                    'top': imgVRelativeOffset * -1
                });
            });
        };

        centerImageVertically();
        $(window).resize(centerImageVertically);
    });
相关问题