我不明白为什么水平方向一切看起来都很完美,但垂直方向正如您在图像中看到的那样,没有边距。如果这适用于网格占据整个宽度:
grid-template-columns: repeat(3, 30%);
为什么这对于获取整个高度不起作用?:
grid-template-rows: repeat(3, 30%);
这是代码:.box 是容器,.card 是子容器:
.box{
/*
margin: 20vh auto;
text-align: center;
width: 75%;
max-width: 650px;
height: 60vh;
*/
display: grid;
grid-template-columns: repeat(3, 30%);
grid-template-rows: repeat(3, 30%);
grid-gap: 12px;
justify-content: center;
}
.card{
border: 2px solid gray;
height: 100%;
border-radius: 6px;
}
<div className="box">
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
</div>
最佳答案
您需要使用 box 类设置容器的高度,并使用 fr 作为单位而不是百分比。您需要容器高度,以便网格单元可以从中计算出它们的高度。如果您使用 fr 而不是百分比,则首先从容器宽度/高度中减去网格间隙,然后根据 grid-template-columns 和 grid-template-rows 的设置划分剩余空间。 这是一个工作示例:
<div class="box">
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
</div>
body {
margin: 0;
}
.box {
background-color: hotpink;
height: 100vh;
width: 100vw;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-gap: 12px;
}
.card{
border: 10px solid gray; // even with 10px or more nothing exceeds the container boundaries any more
//height: 100%; // you do not need this, since the height is being calculated as a fr of the container height
//box-sizing: border-box; // if you decide to set a height nonetheless you have to change box-sizing so the borders are not taking up extra space
background-color: skyblue;
border-radius: 6px;
}
关于html - 为什么 css 网格中的子元素水平占据容器的 100%,而垂直占据容器的 90%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58562840/