Html 缩放图像以适合边界框

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

Scale image to fit a bounding box

htmlcssimageresizeautoresize

提问by Thomas Guillory

Is there a css-only solution to scale an image into a bounding box (keeping aspect-ratio)? This works if the image is bigger than the container:

是否有仅 css 的解决方案将图像缩放到边界框(保持纵横比)?如果图像大于容器,则此方法有效:

img {
  max-width: 100%;
  max-height: 100%;
}

Example:

例子:

But I want to scale up the image until a dimension is 100% of the container.

但我想放大图像,直到尺寸为容器的 100%。

采纳答案by Stephan Muller

Note: Even though this is the accepted answer, the answer belowis more accurate and is currently supported in all browsers if you have the option of using a background image.

注意:尽管这是公认的答案,如果您可以选择使用背景图像,则下面的答案更准确并且当前在所有浏览器中都受支持。

No, there is no CSS only way to do this in both directions. You could add

不,没有 CSS 唯一的方法可以在两个方向上做到这一点。你可以添加

.fillwidth {
    min-width: 100%;
    height: auto;
}

To the an element to always have it 100% width and automatically scale the height to the aspect ratio, orthe inverse:

使元素始终具有 100% 宽度并自动将高度缩放到纵横比,相反:

.fillheight {
    min-height: 100%; 
    width: auto;
}

to always scale to max height and relative width. To do both, you will need to determine if the aspect ratio is higher or lower than it's container, and CSS can't do this.

始终缩放到最大高度和相对宽度。要做到这两点,您需要确定纵横比是高于还是低于它的容器,而 CSS 无法做到这一点。

The reason is that CSS does not know what the page looks like. It sets rules beforehand, but only after that it is that the elements get rendered and you know exactly what sizes and ratios you're dealing with. The only way to detect that is with JavaScript.

原因是 CSS 不知道页面是什么样子。它事先设置规则,但只有在此之后元素才会被渲染并且您确切地知道您正在处理的大小和比例。检测它的唯一方法是使用 JavaScript。



Although you're not looking for a JS solution I'll add one anyway if someone might need it. The easiest way to handle this with JavaScript is to add a class based on the difference in ratio. If the width-to-height ratio of the box is greater than that of the image, add the class "fillwidth", else add the class "fillheight".

尽管您不是在寻找 JS 解决方案,但如果有人可能需要它,我还是会添加一个。用 JavaScript 处理这个问题的最简单方法是根据比率的差异添加一个类。如果框的宽高比大于图像的宽高比,则添加“fillwidth”类,否则添加“fillheight”类。

$('div').each(function() {
  var fillClass = ($(this).height() > $(this).width()) 
    ? 'fillheight'
    : 'fillwidth';
  $(this).find('img').addClass(fillClass);
});
.fillwidth { 
  width: 100%; 
  height: auto; 
}
.fillheight { 
  height: 100%; 
  width: auto; 
}

div {
  border: 1px solid black;
  overflow: hidden;
}

.tower {
  width: 100px;
  height: 200px;
}

.trailer {
  width: 200px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tower">
  <img src="http://placekitten.com/150/150" />
</div>
<div class="trailer">
  <img src="http://placekitten.com/150/150" />
</div>

回答by Thomas Guillory

Thanks to CSS3 there is a solution !

感谢 CSS3 有一个解决方案!

The solution is to put the image as background-imageand then set the background-sizeto contain.

解决方案是将图像放置为background-image,然后将其设置background-sizecontain

HTML

HTML

<div class='bounding-box'>
</div>

CSS

CSS

.bounding-box {
  background-image: url(...);
  background-repeat: no-repeat;
  background-size: contain;
}

Test it here: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain

在这里测试:http: //www.w3schools.com/cssref/playit.asp?filename=playcss_background-size& preval=contain

Full compatibility with latest browsers: http://caniuse.com/background-img-opts

与最新浏览器完全兼容:http: //caniuse.com/background-img-opts

To align the div in the center, you can use this variation:

要在中心对齐 div,您可以使用以下变体:

.bounding-box {
  background-image: url(...);
  background-size: contain;
  position: absolute;
  background-position: center;
  background-repeat: no-repeat;
  height: 100%;
  width: 100%;
}

回答by Vladimir Panteleev

Here's a hackish solution I discovered:

这是我发现的一个骇人听闻的解决方案:

#image {
    max-width: 10%;
    max-height: 10%;
    transform: scale(10);
}

This will enlarge the image tenfold, but restrict it to 10% of its final size - thus bounding it to the container.

这会将图像放大十倍,但将其限制为最终尺寸的 10% - 因此将其限制在容器中。

Unlike the background-imagesolution, this will also work with <video>elements.

background-image解决方案不同,这也适用于<video>元素。

回答by Glenn Maynard

Today, just say object-fit: contain. Support is everything but IE: http://caniuse.com/#feat=object-fit

今天,只说object-fit:contain。支持就是除 IE 之外的一切:http: //caniuse.com/#feat=object-fit

回答by Deke

html:

html:

    <div class="container">
      <img class="flowerImg" src="flower.jpg">
    </div>

css:

css:

.container{
  width: 100px;
  height: 100px;
}


.flowerImg{
  width: 100px;
  height: 100px;
  object-fit: cover;
  /*object-fit: contain;
  object-fit: scale-down;
  object-position: -10% 0;
  object-fit: none;
  object-fit: fill;*/
}

回答by gabrielmaldi

You can accomplish this with pure CSS and complete browser support, both for vertically-long and horizontally-long images at the same time.

您可以使用纯 CSS 和完整的浏览器支持来实现这一点,同时处理垂直长和水平长的图像。

Here's a snippet which works in Chrome, Firefox, and Safari (both using object-fit: scale-down, and without using it):

这是一个适用于 Chrome、Firefox 和 Safari 的代码段(使用object-fit: scale-down和不使用它):

figure {
  margin: 0;
}

.container {
  display: table-cell;
  vertical-align: middle;
  width: 80px;
  height: 80px;
  border: 1px solid #aaa;
}

.container_image {
  display: block;
  max-width: 100%;
  max-height: 100%;
  margin-left: auto;
  margin-right: auto;
}

.container2_image2 {
  width: 80px;
  height: 80px;
  object-fit: scale-down;
  border: 1px solid #aaa;
}
Without `object-fit: scale-down`:

<br>
<br>

<figure class="container">
  <img class="container_image" src="https://i.imgur.com/EQgexUd.jpg">
</figure>

<br>

<figure class="container">
  <img class="container_image" src="https://i.imgur.com/ptO8pGi.jpg">
</figure>

<br> Using `object-fit: scale-down`:

<br>
<br>

<figure>
  <img class="container2_image2" src="https://i.imgur.com/EQgexUd.jpg">
</figure>

<br>

<figure>
  <img class="container2_image2" src="https://i.imgur.com/ptO8pGi.jpg">
</figure>

回答by xerxeArt

Another solution without background image and without the need for a container (though the max sizes of the bounding box must be known):

另一种没有背景图像且不需要容器的解决方案(尽管必须知道边界框的最大尺寸):

img{
  max-height: 100px;
  max-width: 100px;
  width: auto;    /* These two are added only for clarity, */
  height: auto;   /* as the default is auto anyway */
}



如果需要使用容器,则可以将 max-width 和 max-height 设置为 100%:

img {
    max-height: 100%;
    max-width: 100%;
    width: auto; /* These two are added only for clarity, */
    height: auto; /* as the default is auto anyway */
}

div.container {
    width: 100px;
    height: 100px;
}

For this you would have something like:

为此,您将有类似的东西:

<table>
    <tr>
        <td>Lorem</td>
        <td>Ipsum<br />dolor</td>
        <td>
            <div class="container"><img src="image5.png" /></div>
        </td>
    </tr>
</table>

回答by Mr. JCRP

This example to stretch the image proportionally to fit the entire window. An improvisation to the above correct code is to add $( window ).resize(function(){});

本示例按比例拉伸图像以适合整个窗口。对上述正确代码的即兴创作是添加$( window ).resize(function(){});

function stretchImg(){
    $('div').each(function() {
      ($(this).height() > $(this).find('img').height()) 
        ? $(this).find('img').removeClass('fillwidth').addClass('fillheight')
        : '';
      ($(this).width() > $(this).find('img').width()) 
        ? $(this).find('img').removeClass('fillheight').addClass('fillwidth')
        : '';
    });
}
stretchImg();

$( window ).resize(function() {
    strechImg();
});

There are two if conditions. The first one keeps checking if the image height is less than the div and applies .fillheightclass while the next checks for width and applies .fillwidthclass. In both cases the other class is removed using .removeClass()

有两个 if 条件。第一个不断检查图像高度是否小于 div 并应用.fillheight类,而下一个检查宽度并应用.fillwidth类。在这两种情况下,使用删除另一个类.removeClass()

Here is the CSS

这是CSS

.fillwidth { 
   width: 100%;
   max-width: none;
   height: auto; 
}
.fillheight { 
   height: 100vh;
   max-width: none;
   width: auto; 
}

You can replace 100vhby 100%if you want to stretch the image with in a div. This example to stretch the image proportionally to fit the entire window.

如果要在 div 中拉伸图像,可以替换100vh100%。此示例按比例拉伸图像以适合整个窗口。

回答by Robert Eetheart

The cleanest and simplest way to do this:

最干净和最简单的方法来做到这一点:

First some CSS:

首先一些CSS:

div.image-wrapper {
    height: 230px; /* Suggestive number; pick your own height as desired */
    position: relative;
    overflow: hidden; /* This will do the magic */
    width: 300px; /* Pick an appropriate width as desired, unless you already use a grid, in that case use 100% */
}
img {
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
    height: auto;
}

The HTML:

HTML:

<div class="image-wrapper">
  <img src="yourSource.jpg">
</div>

This should do the trick!

这应该可以解决问题!

回答by ericosg

Are you looking to scale upwards but not downwards?

您是否希望向上扩展而不是向下扩展?

div {
    border: solid 1px green;
    width: 60px;
    height: 70px;
}

div img {
    width: 100%;
    height: 100%;
    min-height: 500px;
    min-width: 500px;
    outline: solid 1px red;
}

This however, does not lock aspect-ratio.

但是,这不会锁定纵横比。