您必须稍微调整一下屏幕尺寸才能明白我的意思。 假设我有一张卡片,它位于网格行内,该网格行比卡片高。这张卡片的高度是100%,内部的css网格(元素)也应该是100%的高度。但如果我将
height: 100%
放入网格元素 (.post-card a
) 中,所有行的高度都会受到影响。它们是网格区域。我希望只有最后一个(.bottom-2
)将填充外部网格单元的剩余垂直空间,而“主”内部网格区域仍然尊重我为.image
和.title部分设置的纵横比其内容要高。换句话说,除了最后一行填充空白之外,所有内容都如片段中当前所示。怎么办?
body > div + div{
margin-top: 2em;
}
.grid{
display: grid;
height: 100vh;
}
.post-card{
border: 1px solid #000;
height: 100%;
}
.post-card a{
display: grid;
grid-template-areas:
"main"
"main"
"bottom-1"
"bottom-2";
}
.date{
grid-row: 1/2;
grid-column: 1/2;
width: fit-content;
background-color: #000;
z-index:10;
}
.image{
grid-area: main;
aspect-ratio: 16/3;
background-color: #0e0;
}
.title{
grid-area: bottom-1;
background-color: #0ee;
}
.bottom-2{
grid-area: bottom-2;
display: flex;
background-color: #ee0;
}
.share{
width: 30px;
background-color: #e0e;
}
<div class="grid">
<div class="post-card image-title-cta">
<a href="#">
<div class="date">date</div>
<div class="image">image</div>
<div class="title">title</div>
<div class="bottom-2">
<div class="cta">cta</div>
<div class="share">share</div>
</div>
</a>
</div>
</div>
您需要设置
.post-card a {height: 100%}
是正确的,但为了让行按照您想要的方式运行,您还需要添加 grid-template-rows
样式。
如果我理解正确的话,您希望前三个网格行的大小适合其内容,因此您需要将它们设置为
auto
。然后你希望第四个网格行拉伸以填充网格中的剩余空间,因此需要将其设置为1fr
。分数单位都是关于在满足所有其他约束后如何划分网格中的剩余空间。
.post-card a {
height: 100%;
grid-template-rows: auto auto auto 1fr;
}
演示片段:
body {
margin: 0;
}
body > div + div{
margin-top: 2em;
}
.grid {
display: grid;
height: 100vh;
}
.post-card {
height: 100%;
}
.post-card a {
height: 100%;
display: grid;
grid-template-rows: auto auto auto 1fr;
grid-template-areas:
"main"
"main"
"bottom-1"
"bottom-2";
}
.date{
grid-row: 1/2;
grid-column: 1/2;
width: fit-content;
background-color: #000;
z-index:10;
}
.image {
grid-area: main;
aspect-ratio: 16/3;
background-color: #0e0;
}
.title {
grid-area: bottom-1;
background-color: #0ee;
}
.bottom-2 {
grid-area: bottom-2;
display: flex;
justify-content: space-between;
background-color: #ee0;
}
.share {
background-color: #e0e;
}
<div class="grid">
<div class="post-card image-title-cta">
<a href="#">
<div class="date">date</div>
<div class="image">image</div>
<div class="title">title</div>
<div class="bottom-2">
<div class="cta">cta</div>
<div class="share">share</div>
</div>
</a>
</div>
</div>