宽度全图 - 保持纵横比并保持水平和垂直中心

时间:2014-03-13 16:50:27

标签: html css image

下面的代码有效,但我希望它能保持图像的绝对中心,而不是基于左上角拉伸它。见图:

HTML

 <div class="full-img-container">
 <img src="/images/crowd.jpg" class="full-img">
 </div>

CSS

.full-img-container {
  max-height: 300px;
  overflow: hidden;
}

.full-img {
  width: 100%;
  margin: 0 auto;
  vertical-align:middle;
}

当浏览器很小时:

enter image description here

当浏览器被拉伸时 - 它保持在300px但不是垂直居中(图像中应该有更多人)

enter image description here

更新

这就是我想要做的事:http://demo.solemone.de/overflow-image-with-vertical-centering-for-responsive-web-design/

4 个答案:

答案 0 :(得分:2)

更新:

我想我现在知道你想要什么。有趣的问题。所以垂直居中,由于优先保持图像的中心位于窗口的中心,因此可以裁剪掉图像的顶部和底部。

我找到了一个可以帮助你在另一个网站上的例子:

http://demo.solemone.de/overflow-image-with-vertical-centering-for-responsive-web-design/

试试他的例子,让我知道它是否适合您,或者至少让您更接近理想的解决方案!在收到你的回复后,我会尽力帮助你。

答案 1 :(得分:0)

height: auto;设置为<img>标记。

我想我误解了这个问题。答案是:制作图像块:display: block;

答案 2 :(得分:0)

您可以使用jQuery:

$(window).resize(function(){

    var imgheight = $('.full-img').height();
    var containerheight = $('full-img-container').height();

    heightDifference = imgheight - containerheight;

    if(heightDifference > 0)
    {
        $('.full-img').css('margin-top', '-' + heightDifference/2 + 'px')
    }
});

答案 3 :(得分:0)

你应该尝试设置

background-size:contains;

相关问题