将图像max-width和max-heigth设置为100%但允许图像缩放大于其自身的100%

时间:2018-04-06 09:54:01

标签: javascript css image aspect-ratio

我试图将图片缩放到它父母的100%。图像的纵横比应该保持不变,因此100%比例应该是宽度<100>或 100%高度的100%,以先到者为准。 我尝试过使用

max-height: 100%;
max-width: 100%;

只要图像比它的容器大,这就可以工作。一旦容器变得比图像大,图像就不再延伸到边缘,而是保持在其大小的100%。

浏览器支持是一个问题,我已尝试使用object-fit: contain; 的flexbox,但我必须支持IE10

请考虑以下事项:

&#13;
&#13;
.img-container {
  border: solid red 1px;
  margin-bottom: 10px;
}
.img-container img {
  max-height: 100%;
  max-width: 100%;
  border: solid green 1px;
}
.size1 {
  width: 200px;
  height: 50px;
}
.size2 {
  height: 200px;
  width: 50px;
}
.size3 {
  width: 650px;
  height: 650px;
}
&#13;
<div class="img-container size1">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

<div class="img-container size2">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

<div class="img-container size3">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>
&#13;
&#13;
&#13;

.size1.size2内的图片正确缩放,但.size3的容器大于图片,此图片也应拉伸到边缘。

我该怎么做呢? 纯CSS是首选,但JS不是不可能的。

1 个答案:

答案 0 :(得分:1)

使用jQuery查看此解决方案。

$(document).ready(function(){
 $('img').each(function(){
  let imgHeight = $(this).height();
  let containerHeight = $(this).closest('.img-container').height();
  if(imgHeight > containerHeight){
    $(this).css('width','auto');
    $(this).css('height', '100%');
  }
 });
});
.img-container {
  border: solid red 1px;
  margin-bottom: 10px;
}
.img-container img {
  width: 100%;
  height: auto;
  border: solid green 1px;
}
.size1 {
  width: 200px;
  height: 50px;
}
.size2 {
  height: 200px;
  width: 50px;
}
.size3 {
  width: 650px;
  height: 650px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img-container size1">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

<div class="img-container size2">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

<div class="img-container size3">
 <img src="https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>

相关问题