Html 是否有与 background-size:cover 和 contains 等效的图像元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11670874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:50:46  来源:igfitidea点击:

Is there an equivalent to background-size: cover and contain for image elements?

htmlimagecss

提问by stormpat

I have a site with many pages and different background pictures, and I display them from CSS like:

我有一个包含许多页面和不同背景图片的网站,我从 CSS 中显示它们,例如:

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

However, I want to show different (fullscreen) pictures on one page using <img>elements, and I want them to have the same properties as the above background-image: cover;property (the images cant be displayed from CSS, they must be displayed from the HTML document).

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

Normally I use:

通常我使用:

div.mydiv img {
    width: 100%;
}

Or:

或者:

div.mydiv img {
    width: auto;
}

to make the picture full and responsive. However the picture shrinks too much (width: 100%) when the screen gets too narrow, and shows the body's background-color in the bottom screen. The other method, width: auto;, only makes the image full size and does not respond to the screen size.

使图片完整和响应。但是,width: 100%当屏幕太窄时,图片会缩小太多 ( ),并在底部屏幕中显示主体的背景颜色。另一种方法,width: auto;,只使图像全尺寸并且不响应屏幕尺寸。

Is there a way to display the image the same way that background-size: coverdoes?

有没有办法以相同的方式显示图像background-size: cover

回答by Danield

Solution #1 - The object-fit property(Lacks IE support)

解决方案 #1 - object-fit 属性缺乏 IE 支持

Just set object-fit: cover;on the img .

只需object-fit: cover;在 img 上设置。

body {
  margin: 0;
}
img {
  display: block;
  width: 100vw;
  height: 100vh;
  object-fit: cover;
}
<img src="http://lorempixel.com/1500/1000" />

See MDN- regarding object-fit: cover:

请参阅MDN- 关于object-fit: cover

The replaced content is sized to maintain its aspect ratio while filling the element's entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.

在填充元素的整个内容框时,替换内容的大小会保持其纵横比。如果对象的纵横比与其框的纵横比不匹配,则对象将被裁剪以适应。

Also, see this Codepen demowhich compares object-fit: coverapplied to an image with background-size: coverapplied to a background image

另外,请参阅此 Codepen 演示,它比较了object-fit: cover应用于图像和background-size: cover应用于背景图像



Solution #2 - Replace the img with a background image with css

解决方案#2 - 将 img 替换为带有 css 的背景图像

body {
  margin: 0;
}
img {
  position: fixed;
  width: 0;
  height: 0;
  padding: 50vh 50vw;
  background: url(http://lorempixel.com/1500/1000/city/Dummy-Text) no-repeat;
  background-size: cover;
}
<img src="http://placehold.it/1500x1000" />

回答by Simon

There is actually quite a simple css solutionwhich even works on IE8:

实际上有一个非常简单的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>

回答by Ulrich Schwarz

Assuming you can arrange to have a container element you wish to fill, this appears to work, but feels a bit hackish. In essence, I just use min/max-width/heighton a larger area and then scale that area back into the original dimensions.

假设你可以安排一个你想要填充的容器元素,这看起来可行,但感觉有点hackish。本质上,我只是min/max-width/height在更大的区域上使用,然后将该区域缩放回原始尺寸。

.container {
  width: 800px;
  height: 300px;
  border: 1px solid black;
  overflow:hidden;
  position:relative;
}
.container.contain img {
  position: absolute;
  left:-10000%; right: -10000%; 
  top: -10000%; bottom: -10000%;
  margin: auto auto;
  max-width: 10%;
  max-height: 10%;
  -webkit-transform:scale(10);
  transform: scale(10);
}
.container.cover img {
  position: absolute;
  left:-10000%; right: -10000%; 
  top: -10000%; bottom: -10000%;
  margin: auto auto;
  min-width: 1000%;
  min-height: 1000%;
  -webkit-transform:scale(0.1);
  transform: scale(0.1);
}
<h1>contain</h1>
  <div class="container contain">
    <img 
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" 
       />
    <!-- 366x200 -->
  </div>
  <h1>cover</h1>
  <div class="container cover">
    <img 
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" 
       />
    <!-- 366x200 -->
  </div>

回答by Thiago Barcala

I found a simple solution to emulate both cover and contain, which is pure CSS, and works for containers with dynamic dimensions, and also doesn't make any restriction on the image ratio.

我找到了一个模拟封面和包含的简单解决方案,它是纯 CSS,适用于具有动态尺寸的容器,并且对图像比例没有任何限制。

Note that if you don't need to support IE, or Edge before 16, then you better use object-fit.

注意,如果你不需要支持 IE,或者 16 之前的 Edge,那么你最好使用 object-fit。

background-size: cover

背景尺寸:封面

.img-container {
  position: relative;
  overflow: hidden;
}

.background-image {
  position: absolute;
  min-width: 1000%;
  min-height: 1000%;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%) scale(0.1);
  z-index: -1;
}
<div class="img-container">
  <img class="background-image" src="https://picsum.photos/1024/768/?random">
  <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
</div>

The 1000% is used here in case the image natural size is bigger than the size it is being displayed. For example, if the image is 500x500, but the container is only 200x200. With this solution, the image will be resized to 2000x2000 (due to min-width/min-height), then scaled down to 200x200 (due to transform: scale(0.1)).

此处使用 1000% 以防图像自然尺寸大于其显示尺寸。例如,如果图像是 500x500,但容器只有 200x200。使用此解决方案,图像将被调整为 2000x2000(由于最小宽度/最小高度),然后缩小到 200x200(由于transform: scale(0.1))。

The x10 factor can be replaced by x100 or x1000, but it is usually not ideal to have a 2000x2000 image being rendered on a 20x20 div. :)

x10 因子可以用 x100 或 x1000 代替,但在 20x20 div 上渲染 2000x2000 图像通常并不理想。:)

background-size: contain

背景大小:包含

Following the same principle, you can also use it to emulate background-size: contain:

遵循相同的原则,您也可以使用它来模拟background-size: contain

.img-container {
  position: relative;
  overflow: hidden;
  z-index: 0;
}

.background-image {
  position: absolute;
  max-width: 10%;
  max-height: 10%;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%) scale(10);
  z-index: -1;
}
<div style="background-color: black">
  <div class="img-container">
    <img class="background-image" src="https://picsum.photos/1024/768/?random">
    <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>
</div>

回答by roo2

No, you can't get it quite like background-size:coverbut..

,你不能完全理解它,background-size:cover但是..

This approach is pretty damn close: it uses JavaScript to determine if the image is landscape or portrait, and applies styles accordingly.

这种方法非常接近:它使用 JavaScript 来确定图像是横向还是纵向,并相应地应用样式。

JS

JS

 $('.myImages img').load(function(){
        var height = $(this).height();
        var width = $(this).width();
        console.log('widthandheight:',width,height);
        if(width>height){
            $(this).addClass('wide-img');
        }else{
            $(this).addClass('tall-img');
        }
    });

CSS

CSS

.tall-img{
    margin-top:-50%;
    width:100%;
}
.wide-img{
    margin-left:-50%;
    height:100%;
}

http://jsfiddle.net/b3PbT/

http://jsfiddle.net/b3PbT/

回答by Gus

I needed to emulate background-size: contain, but couldn't use object-fitdue to the lack of support. My images had containers with defined dimensions and this ended up working for me:

我需要模拟background-size: contain,但object-fit由于缺乏支持而无法使用。我的图像具有定义尺寸的容器,这最终对我有用:

.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>

回答by Jeremy

Try setting bothmin-heightand min-width, with display:block:

尝试设置min-heightmin-width,用display:block

img {
    display:block;
    min-height:100%;
    min-width:100%;
}

(fiddle)

小提琴

Provided your image's containing element is position:relativeor position:absolute, the image will cover the container. However, it will not be centred.

如果图像的包含元素是position:relativeposition:absolute,则图像将覆盖容器。但是,它不会居中。

You can easily centre the image if you know whether it will overflow horizontally (set margin-left:-50%) or vertically (set margin-top:-50%). It may be possible to use CSS media queries (and some mathematics) to figure that out.

如果您知道图像会水平溢出(set margin-left:-50%)还是垂直溢出(set ),则可以轻松地将图像居中margin-top:-50%。可以使用 CSS 媒体查询(和一些数学)来解决这个问题。

回答by mems

With CSS you can simulate object-fit: [cover|contain];. It's use transformand [max|min]-[width|height]. It's not perfect.That not work in one case: if the image is wider and shorter than the container.

使用 CSS,您可以模拟object-fit: [cover|contain];. 它的用途transform[max|min]-[width|height]这并不完美。这在一种情况下不起作用:如果图像比容器更宽和更短。

.img-ctr{
  background: red;/*visible only in contain mode*/
  border: 1px solid black;
  height: 300px;
  width: 600px;
  overflow: hidden;
  position: relative;
  display: block;
}
.img{
  display: block;

  /*contain:*/
  /*max-height: 100%;
  max-width: 100%;*/
  /*--*/

  /*cover (not work for images wider and shorter than the container):*/
  min-height: 100%;
  width: 100%;
  /*--*/

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<p>Large square:
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x1000"></span>
</p>
<p>Small square:
<span class="img-ctr"><img class="img" src="http://placehold.it/100x100"></span>
</p>
<p>Large landscape:
<span class="img-ctr"><img class="img" src="http://placehold.it/2000x1000"></span>
</p>
<p>Small landscape:
<span class="img-ctr"><img class="img" src="http://placehold.it/200x100"></span>
</p>
<p>Large portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x2000"></span>
</p>
<p>Small portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/100x200"></span>
</p>
<p>Ultra thin portrait:
<span class="img-ctr"><img class="img" src="http://placehold.it/200x1000"></span>
</p>
<p>Ultra wide landscape (images wider and shorter than the container):
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x200"></span>
</p>

回答by Charlie Tupman

What you could do is use the 'style' attribute to add the background image to the element, that way you will still be calling the image in the HTML but you will still be able to use the background-size: cover css behaviour:

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

HTML:

HTML:

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

CSS:

CSS:

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

This is how I add the background-size: cover behaviour to elements that I need to dynamically load into HTML. You can then use awesome css classes like background-position: center. boom

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

回答by Asim Ramay

im not allowed to 'add a comment' so doing this , but yea what Eru Penkman did is pretty much spot on , to get it like background cover all you need to do is change

我不允许“添加评论”,所以这样做,但是 Eru Penkman 所做的几乎是正确的,要让它像背景封面一样,你需要做的就是改变

.tall-img{
    margin-top:-50%;
    width:100%;
}
.wide-img{
    margin-left:-50%;
    height:100%;
}

TO

.wide-img{
    margin-left:-42%;
    height:100%;
}
.tall-img{
    margin-top:-42%;
    width:100%;
}