我有一个网站,有许多页面和不同的背景图片,我从CSS显示它们,像这样:

body.page-8 {
    background: url("../img/pic.jpg") no-repeat scroll center top #000;
    background-size: cover;
}

但是,我想在一个页面上使用<img>元素显示不同的(全屏)图片,并且我希望它们具有与上面的background-image相同的属性:cover;属性(图像不能显示从CSS,他们必须显示从HTML文档)。

通常我使用:

div.mydiv img {
    width: 100%;
}

Or:

div.mydiv img {
    width: auto;
}

使画面饱满,反应灵敏。然而,当屏幕变得太窄时,图片会收缩太多(宽度:100%),并在底部屏幕显示身体的背景色。另一种方法width: auto;只使图像完全大小,不响应屏幕大小。

是否有一种方法可以像background-size: cover那样显示图像?


当前回答

我们可以采用ZOOM方法。我们可以假设,如果方面图像的高度或宽度小于所需的高度或宽度,最大30%(或更高至100%)可以是缩放效果。我们可以用overflow: hidden隐藏其他不需要的区域。

.image-container {
  width: 200px;
  height: 150px;
  overflow: hidden;
}
.stage-image-gallery a img {
  max-height: 130%;
  max-width: 130%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

这将调整不同宽度或高度的图像。

其他回答

实际上有一个非常简单的css解决方案,甚至可以在IE8上工作:

.container { position: relative; overflow: hidden; /* Width and height can be anything. */ width: 50vw; height: 50vh; } img { position: absolute; /* Position the image in the middle of its container. */ top: -9999px; right: -9999px; bottom: -9999px; left: -9999px; margin: auto; /* The following values determine the exact image behaviour. */ /* You can simulate background-size: cover/contain/etc. by changing between min/max/standard width/height values. These values simulate background-size: cover */ min-width: 100%; min-height: 100%; } <div class="container"> <img src="http://placehold.it/200x200" alt="" /> </div>

我不允许'添加一个评论'这样做,但是的,什么Eru Penkman做的是相当到位,让它像背景覆盖所有你需要做的就是改变

.tall-img { margin-top: -50%; 宽度:100%; } .wide-img { margin-left: -50%; 高度:100%; }

TO

.wide-img { margin-left: -42%; 高度:100%; } .tall-img { margin-top: -42%; 宽度:100%; }

我需要模拟background-size: contains,但由于缺乏支持,不能使用对象匹配。我的图像有定义尺寸的容器,这最终为我工作:

.image-container { height: 200px; width: 200px; overflow: hidden; background-color: rebeccapurple; border: 1px solid yellow; position: relative; } .image { max-height: 100%; max-width: 100%; margin: auto; position: absolute; transform: translate(-50%, -50%); top: 50%; left: 50%; } <!-- wide --> <div class="image-container"> <img class="image" src="http://placehold.it/300x100"> </div> <!-- tall --> <div class="image-container"> <img class="image" src="http://placehold.it/100x300"> </div>

你能做的是使用'style'属性将背景图像添加到元素中,这样你仍然会在HTML中调用图像,但你仍然能够使用background-size: cover css行为:

HTML:

    <div class="image-div" style="background-image:url(yourimage.jpg)">
    </div>

CSS:

    .image-div{
    background-size: cover;
    }

这就是我如何将background-size: cover行为添加到我需要动态加载到HTML中的元素。然后你可以使用很棒的css类,如background-position: center。繁荣

我们可以采用ZOOM方法。我们可以假设,如果方面图像的高度或宽度小于所需的高度或宽度,最大30%(或更高至100%)可以是缩放效果。我们可以用overflow: hidden隐藏其他不需要的区域。

.image-container {
  width: 200px;
  height: 150px;
  overflow: hidden;
}
.stage-image-gallery a img {
  max-height: 130%;
  max-width: 130%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

这将调整不同宽度或高度的图像。