我有一个已知大小的方形 div。
我想显示一张大小未知的图片。
我要:
.在保持图片大小比例的情况下,利用div中的最大空间展示图片。
.要居中的图像,如果图像高大于宽则水平居中,或者如果图像宽大于高则垂直居中。
.我不希望图像被裁剪
.我不希望图像被拉伸(stretch)并使用整个 div
.图像应保持其比例
我可以使用 html img 标签或 CSS 背景图片属性
最佳答案
感谢@CBroe 和他使用背景大小的建议,我找到了解决方案
.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>
关于html - 以已知大小在 div 中居中图像。使用所有高度或所有宽度。保持正确的比例。没有裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40847278/