例如,如果容器的类型为 block ,这将生成适合其容器的图像:
#image {
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
}
但是,如果图像是具有固定大小行的网格的一部分(这里是 a plunk 以查看它的实际效果),则它不起作用,例如:
<style>
#container {
display: grid;
grid-auto-columns: 0.3fr;
grid-auto-rows: 80px;
}
.image {
border: 1px solid black;
max-width: 100%;
max-height: 100%;
height: auto;
width: auto;
}
.image:nth-child(1) {
grid-column: 1;
grid-row: 1;
}
.image:nth-child(2) {
grid-column: 1;
grid-row: 2;
}
</style>
<div id="container">
<img class="image" src="http://via.placeholder.com/1366x768">
<img class="image" src="http://via.placeholder.com/1366x768">
</div>
在这个例子中,两个图像都超出了它们的盒子,我希望两个图像的行为就像它们在单独的容器中一样:
#container {
display: block;
height: 80px;
}
基本上我的问题是,有没有一种方法可以设置图像的样式,以便它们可以缩放以适合任何网格单元格(无论该单元格是使用 auto
还是固定大小)以便它们自动缩小以适合单元格,同时保持纵横比(就像它们可以在 block 容器中缩小一样)?
最佳答案
这似乎是一个 Chrome bug而不是我在 max-height
上做错了什么,所以没有对此采取进一步的行动。
关于css - 是否可以在保持宽高比的同时让图像在 CSS 网格中自动调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782170/