在 IE 11 中使用最大宽度和最大高度保持图像比例

Keep image ratio using max-width and max-height in IE 11

我正在尝试让图像适合容器,同时保持其大小比例。图像应根据方向占据全高或全宽。我的解决方案适用于我测试过的所有浏览器,但 IE11(令人惊讶地适用于 10 和 9)。

在 IE 11 中,图像在右侧被裁剪。如果可能的话,我想要一种纯粹的 css 方式,而且我不关心它是否居中。

这是 JSFiddle:https://jsfiddle.net/wagad0u8/

<div class="owl-item" style="width: 465px;">
  <a class="img-flux" href="page1.html">
    <img alt="omg" src="http://placehold.it/1000x100">
  </a>
</div>

<div class="owl-item" style="width: 465px;">
  <a class="img-flux" href="page1.html">
    <img alt="omg" src="http://placehold.it/400x780">
  </a>
</div>

.img-flux img {
    border: 0;
    max-height: 100%;
    max-width: 100%;
    height: auto;
    width: auto;
    position: relative;
    transition: all 0.3s;
    margin: 0 auto;
    float: none;
    display: block;
    vertical-align:middle;
}
#content-block *:last-child {
    margin-bottom: 0px;
}
.owl-item, .owl-item .img-flux {
    height: 100%;
}
.img-flux {
    background-color: #ECECEC;
    position: relative;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}
.owl-item{
  float:left;
  height:300px;
  margin-bottom:50px;
}

使用

vw - for width instead of %

vh - for height instead of %

在 IE11 等旧版本中受支持。

https://jsfiddle.net/wagad0u8/1/

要仅将更改后的代码应用于 IE10+,请使用:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
/* IE10+ */
.img-flux img {
max-width : 100vw;
max-height : 100vh;
}
.img-flux img {
    border: 0;
    max-height: 100%;
    max-width: 100%;
    height: auto;
    width: 100%;
    position: relative;
    transition: all 0.3s;
    margin: 0 auto;
    float: none;
    display: block;
    vertical-align: middle;
}

这似乎是 IE11 中的错误:Bug Report。添加 flex: 1(如报告中所述)

.img-flux img {
    flex: 1;
    max-width: 100%;
    max-height: 100%;
}

适合我。父级的 Flexbox 似乎还可以,所以即使居中也很容易。

另一种选择是

flex: 0 0 auto;  /* IE */
object-fit: scale-down; /* FF */

img 上,而不是 flex: 1 上,增加了与 Firefox 的兼容性。有关详细信息,请参阅评论和错误报告。