已知大小的div中心图像。使用所有高度或所有宽度。保持正确的比例。没有作物

时间:2016-11-28 14:57:32

标签: html css image css3

我有一个已知大小的方形div。

我想在其中显示尺寸未知的图片。

我想:

。使用div中的最大空间来显示图像,同时保持图像的大小比例。

。要成像的图像,如果图像比较宽则水平,或者如果图像宽度大于垂直则垂直。

。我不希望裁剪图像

。我不希望图像被拉伸并使用整个div

。图像应保持其比例

我可以使用html img标签或CSS背景图片属性

2 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,感谢@CBroe和他建议使用background-size



.container {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background-repeat: no-repeat;
  background-position: center; 
  background-size: contain;
}

.container1 {
  background-image: url('http://placehold.it/30x50');
}
.container2 {
  background-image: url('http://placehold.it/50x30');
}
.container3 {
  background-image: url('http://placehold.it/500x300');
}
.container4 {
  background-image: url('http://placehold.it/300x500');
}

<div class="container container1">
</div>
<div class="container container2">
</div>
<div class="container container3">
</div>
<div class="container container4">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
.container {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  
  position: relative;
}
img {
  max-width: 100px;
  max-height: 100px;
  
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    
}
&#13;
<div class="container">
  <img src="http://placehold.it/30x50" />
</div>
<div class="container">
  <img src="http://placehold.it/50x30" />
</div>

<div class="container">
  <img src="http://placehold.it/500x300" />
</div>
<div class="container">
  <img src="http://placehold.it/300x500" />
</div>
&#13;
&#13;
&#13;