Html 如何在保持图像的纵横比的同时拉伸图像以填充 <div> ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1891857/
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:32:43  来源:igfitidea点击:

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

imagehtmlsize

提问by Giffyguy

I need to make this image stretch to the maximum size possible without overflowing it's <div>or skewing the image.

我需要将此图像拉伸到可能的最大尺寸,而不会溢出<div>或扭曲图像。

I can't predict the aspect-ratio of the image, so there's no way to know whether to use:

我无法预测图像的纵横比,因此无法知道是否使用:

<img src="url" style="width: 100%;">

or

或者

<img src="url" style="height: 100%;">

I can't use both (i.e. style="width: 100%; height: 100%;") because that will stretch the image to fit the <div>.

我不能同时使用两者(即 style="width: 100%; height: 100%;"),因为这会拉伸图像以适合<div>.

The <div>has a size set by percentage of the screen, which is also unpredictable.

<div>具有由屏幕,这也是不可预测的百分比尺寸集。

采纳答案by Mottie

Update 2016:

2016 年更新:

Modern browser behave much better. All you should need to do is to set the image width to 100% (demo)

现代浏览器的表现要好得多。您需要做的就是将图像宽度设置为 100%(演示

.container img {
   width: 100%;
}


Since you don't know the aspect ratio, you'll have to use some scripting. Here is how I would do it with jQuery (demo):

由于您不知道纵横比,因此您必须使用一些脚本。这是我将如何使用 jQuery ( demo):

CSS

CSS

.container {
    width: 40%;
    height: 40%;
    background: #444;
    margin: 0 auto;
}
.container img.wide {
    max-width: 100%;
    max-height: 100%;
    height: auto;
}
.container img.tall {
    max-height: 100%;
    max-width: 100%;
    width: auto;
}?

HTML

HTML

<div class="container">
 <img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>
<br />
<br />
<div class="container">
 <img src="http://i47.tinypic.com/i1bek8.jpg" />
</div>

Script

脚本

$(window).load(function(){
 $('.container').find('img').each(function(){
  var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
  $(this).addClass(imgClass);
 })
})

回答by Ryan

There is a much easier way to do this using only CSSand HTML:

有一种更简单的方法可以只使用CSSand来做到这一点HTML

HTML:

HTML:

<div class="fill"></div>

CSS:

CSS:

.fill {
    overflow: hidden;
    background-size: cover;
    background-position: center;
    background-image: url('path/to/image.jpg');
}

This will place your image as the background, and stretch it to fit the divsize without distortion.

这会将您的图像作为背景,并将其拉伸以适应div尺寸而不会失真。

回答by Prouda

Not a perfect solution, but this CSS might help. The zoom is what makes this code work, and the factor should theoretically be infinite to work ideally for small images - but 2, 4, or 8 works fine in most cases.

不是一个完美的解决方案,但这个 CSS 可能会有所帮助。缩放是使此代码起作用的原因,理论上该系数应该是无限的,才能理想地用于小图像 - 但在大多数情况下,2、4 或 8 可以正常工作。

#myImage {
    zoom: 2;  //increase if you have very small images

    display: block;
    margin: auto;

    height: auto;
    max-height: 100%;

    width: auto;
    max-width: 100%;
}

回答by daniels

If you can, use background images and set background-size: cover. This will make the background cover the whole element.

如果可以,请使用背景图像并设置background-size: cover. 这将使背景覆盖整个元素。

CSS

CSS

div {
  background-image: url(path/to/your/image.png);
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: cover;
}

If you're stuck with using inline images there are a few options. First, there is

如果您坚持使用内联图像,则有几个选项。首先,有

object-fit

对象适合

This property acts on images, videos and other objects similar to background-size: cover.

此属性作用于图像、视频和其他类似于 的对象background-size: cover

CSS

CSS

img {
  object-fit: cover;
}

Sadly, browser supportis not that great with IE up to version 11 not supporting it at all. The next option uses jQuery

可悲的是,浏览器支持并不是那么好,IE 版本 11 根本不支持它。下一个选项使用 jQuery

CSS + jQuery

CSS + jQuery

HTML

HTML

<div>
  <img src="image.png" class="cover-image">
</div>

CSS

CSS

div {
  height: 8em;
  width: 15em;
}

Custom jQuery plugin

自定义jQuery 插件

(function ($) {
  $.fn.coverImage = function(contain) {
    this.each(function() {
      var $this = $(this),
        src = $this.get(0).src,
        $wrapper = $this.parent();

      if (contain) {
        $wrapper.css({
          'background': 'url(' + src + ') 50% 50%/contain no-repeat'
        });
      } else {
        $wrapper.css({
          'background': 'url(' + src + ') 50% 50%/cover no-repeat'
        });
      }

      $this.remove();
    });

    return this;
  };
})(jQuery);

Use the plugin like this

像这样使用插件

jQuery('.cover-image').coverImage();

It will take an image, set it as a background image on the image's wrapper element and remove the imgtag from the document. Lastly you could use

它将获取一张图片,将其设置为图片包装元素上的背景图片,并img从文档中删除标签。最后你可以使用

Pure CSS

纯 CSS

You might use this as a fallback. The image will scale up to cover it's container but it won't scale down.

您可以将其用作后备。图像将放大以覆盖其容器,但不会缩小。

CSS

CSS

div {
  height: 8em;
  width: 15em;
  overflow: hidden;
}

div img {
  min-height: 100%;
  min-width: 100%;
  width: auto;
  height: auto;
  max-width: none;
  max-height: none;
  display: block;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Hope this might help somebody, happy coding!

希望这可以帮助某人,快乐编码!

回答by It_Never_Works

Thanks to CSS3

感谢 CSS3

img
{
   object-fit: contain;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

IE and EDGE as always outsiders: http://caniuse.com/#feat=object-fit

IE 和 EDGE 一如既往的局外人:http: //caniuse.com/#feat=object-fit

回答by Ed Stennett

Update 2019.

2019 年更新。

You can now use the object-fitcss property that accepts the following values: fill | contain | cover | none | scale-down

您现在可以使用object-fit接受以下值的css 属性:fill | contain | cover | none | scale-down

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

As an example, you could have a container that holds an image.

例如,您可以拥有一个包含图像的容器。

<div class="container">
    <img src="" class="container_img" />
</div>

.container {
    height: 50px;
    width: 50%;

.container_img {
    height: 100%;
    width: 100%;
    object-fit: cover;

回答by Tatu Ulmanen

That's impossible with just HTML and CSS, or at least wildly exotic and complicated. If you're willing to throw some javascript in, here's a solution using jQuery:

仅使用 HTML 和 CSS,或者至少是异国情调和复杂的,这是不可能的。如果您愿意投入一些 javascript,这里有一个使用 jQuery 的解决方案:

$(function() {
    $(window).resize(function() {
        var $i = $('img#image_to_resize');
        var $c = $img.parent();
        var i_ar = $i.width() / $i.height(), c_ar = $c.width() / $c.height();            
        $i.width(i_ar > c_ar ? $c.width() : $c.height() * (i_ar));
    });
    $(window).resize();
});

That will resize the image so that it will always fit inside the parent element, regardless of it's size. And as it's binded to the $(window).resize()event, when user resizes the window, the image will adjust.

这将调整图像的大小,使其始终适合父元素,无论其大小如何。并且由于它绑定到$(window).resize()事件,当用户调整窗口大小时,图像将进行调整。

This does not try to center the image in the container, that would be possible but I guess that's not what you're after.

这不会尝试将图像在容器中居中,这是可能的,但我想这不是您想要的。

回答by Chintan Bhatt

Set width and height of the outer containerdiv. Then use below styling on img:

设置外部containerdiv 的宽度和高度。然后在 img 上使用以下样式:

.container img{
    width:100%;
    height:auto;
    max-height:100%;
}

This will help you to keep an aspect ratio of your img

这将帮助您保持 img 的纵横比

回答by Bohao LI

If you want to set a max width or height (so that it will not be very large) while keeping the images aspect-ratio, you can do this:

如果要在保持图像纵横比的同时设置最大宽度或高度(使其不会很大),您可以这样做:

img{
   object-fit: contain;
   max-height: 70px;
}

回答by ianbeans

To make this image stretch to the maximum size possible without overflowingit's or skewing the image.

为了使该图像拉伸到可能最大尺寸,而不会溢出或扭曲图像。

Apply...

申请...

img {
  object-fit: cover;
  height: -webkit-fill-available;
}

styles to the image.

样式到图像。