假设我有以下代码:
img {
max-widht: 100%;
max-height: 100%;
}
<div width="500" height="500">
<img src="https://placehold.it/250x150">
</div>
如果 width
或 height
大于 500px,这对所有图像都有效。
但是对于较小的图像,图像将不会覆盖 div
。
有没有一种 CSS 方法可以强制图像至少为 width: 100%
或 height: 100%
而不管其原始大小?
编辑: 此解决方案由 disinfor为我工作。
img {
width: 100%;
height: 100%;
object-fit: contain;
}
最佳答案
这样做:
img {
width: 100%;
height: auto;
}
较小的图像(在您的例子中,宽度小于 500 像素)没有填满整个空间的原因是因为 max-width
表示“实际图像的最大宽度”。因此,如果您改用 width: 100%
,图像将填满其容器的空间。
使用 height: auto
将确保图像不会被垂直拉伸(stretch)/扭曲。
概念验证:
.normal, .land, .port, .fit {
height: 200px;
width: 200px;
}
img {
width: 100%;
height: auto;
}
div.land img,
div.port img {
width: 100%;
height: 100%;
}
div.fit img {
width: 100%;
height: 100%;
object-fit: cover;
}
<div class="fit">
<img src="https://placehold.it/500x750">
</div>
<div class="fit">
<img src="https://placehold.it/50x100">
</div>
<div class="normal">
<img src="https://placehold.it/75x10">
</div>
<div class="normal">
<img src="https://placehold.it/10x75">
</div>
<div class="land">
<img src="https://placehold.it/75x10">
</div>
<div class="port">
<img src="https://placehold.it/10x75">
</div>
关于html - 如何使图像适合其 div CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54934081/