如何在网格中的div中缩放图像



我使用的是网格布局。我用grid-template-columngrid-template-rows来定义它的结构。我希望第一个单元格包含一个图像。由于我想将其水平居中,所以我的想法是将其放置在div中,div本身可以是flex或grid容器。

我在缩放图像时遇到问题。当不使用div时,我基本上是将图像直接放置在网格内,我可以使用height: 100%;,它会向下缩放,以使高度适合单元格。

但是当使用一个不再工作的额外div容器时。使用height: 100%似乎是指整个网格布局的高度,而不仅仅是div。谷歌说我应该使用max-heightmax-width,但我无法使用它。下面是一个简单的测试项目(HTML和CSS(来显示这个问题。当使用width: 25px;时,你可以看到网格的部分应该有多大。

我感谢你的帮助。请记住,这是一个简单的测试项目,所以不要介意我的类和ID的命名。

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body,
html {
height: 100%;
}
.class {
background-color: blue;
}
.container {
height: 100vh;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr 3fr 3fr;
gap: 10px;
background-color: green;
}
#image-container>img {
max-height: 100%;
}
<div class="container">
<div class="class" id="image-container">
<img src="https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg" alt="">
</div>
<div class="class" id="2">Good</div>
<div class="class" id="3">Day</div>
</div>

检查子元素类上的溢出和父元素上的最大高度,以获得所需的结果。

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body,
html {
min-height: 100%;
}
.parent {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr repeat(2, 3fr);
gap: 1rem;
background: orchid;
max-width: 100%;
max-height: 100vh;
}
.class{
background: teal;
overflow: hidden;
}
img{
display:block;
width: 100%;
height: 100%;
object-fit: cover;
}
<div class="parent">
<div class="class">
<img src="https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg" alt="">
</div>
<div class="class">
<p>Good</p>
</div>
<div class="class">
<p>Day</p>
</div>
</div>

我的首选方法是将其设置为背景图像,背景大小为:包含(或覆盖(。这应用了浏览器的逻辑,而不是自己尝试正确处理,并且是完全响应的。

.exampleA, .exampleB{
width: 34%;
height: 150px;
background-position: center;
background-repeat: no-repeat;
background-color: pink;  /* Just for this demo:  to display canvas size */
border: 1px solid black; /* Just for this demo */
display: inline-block;
}
.exampleA {
background-size: contain;
}
.exampleB {
background-size: cover;
}
<div class="exampleA"
style="background-image: url('https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg');"
></div>

<div class="exampleB"
style="background-image: url('https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg');"
></div>

最新更新