的原始空间。
>我使用 CSS 网格将我的.grid
元素分为 4 列和 4 行。我调整了图像,使其位于第一列和第 4 行。但是,正如你所看到的,一个男人的形象超过了.grid
<div>
的原始高度,它重叠并越过它下面的另一个元素。
如何将图像保持.grid
的原始大小并将其与第一列和第 4 行对齐?(我也希望它粘在黑色元素的顶部,但不重叠(。
.grid {
height: 1000px;
width: 100%;
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-template-rows: 25% 25% 25% 25%;
}
#image {
grid-column: 1;
grid-row: 4;
}
.box {
background: black;
height: 500px;
}
<div class="grid">
<div id="image">
<img src="https://futhead.cursecdn.com/static/img/14/players/176619.png"/>
</div>
</div>
<div class="box"></div>
将max-width:100%
应用于img
,以便它可以采用列宽的宽度
.grid {
height: 1000px;
width: 100%;
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-template-rows: 25% 25% 25% 25%;
}
#image {
grid-column: 1;
grid-row: 4;
}
.box {
background: black;
height: 500px;
}
#image img {
max-width: 100%;
}
<div class="grid">
<div id="image">
<img src="https://futhead.cursecdn.com/static/img/14/players/176619.png" />
</div>
</div>
<div class="box"></div>
您需要约束<img>
以保持其父高度和宽度。
* {
margin: 0;
padding: 0;
}
.grid {
height: 1000px;
width: 100%;
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-template-rows: 25% 25% 25% 25%;
}
#image {
grid-column: 1;
grid-row: 4;
}
.box {
background: black;
height: 500px;
}
/* Added */
#image>img {
width: 100%;
height: 100%;
}
<div class="grid">
<div id="image">
<img src="https://futhead.cursecdn.com/static/img/14/players/176619.png" />
</div>
</div>
<div class="box"></div>
由于容器的高度为 1000px,并且每行设置为 25%,因此每行的高度为 250px。
使用该信息,您可以设置图像的高度,同时保持纵横比并使用object-fit
属性填充整个框。
.grid {
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-template-rows: 25% 25% 25% 25%;
height: 1000px;
}
#image {
grid-column: 1;
grid-row: 4;
}
#image > img {
width: 100%;
height: 250px;
object-fit: cover;
}
.box {
background: black;
height: 500px;
}
<div class="grid">
<div id="image">
<img src="https://futhead.cursecdn.com/static/img/14/players/176619.png" />
</div>
</div>
<div class="box"></div>