html - 为什么 css 网格中的子元素水平占据容器的 100%,而垂直占据容器的 90%?

标签 html css css-grid

我不明白为什么水平方向一切看起来都很完美,但垂直方向正如您在图像中看到的那样,没有边距。如果这适用于网格占据整个宽度:

 grid-template-columns: repeat(3, 30%);

为什么这对于获取整个高度不起作用?:

grid-template-rows: repeat(3, 30%);

enter image description here

这是代码:.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/

相关文章:

html - CSS 定位 - 从 float 元素填充空白

javascript - 为什么 jquery 不工作?

javascript - Bootstrap 设置弹出框内容

html - 为什么我的 css 网格中的最后一行元素移位了?

css - 在 CSS-Grid-Layout 中使用 Angular *ngFor?

css - 向左浮动移动到错误的地方

html - div 显示内图像的自动宽度 :table so they are of the same height

html - CSS 网格,一些媒体查询不适用

PHP : Logical query with some complications

javascript - 我如何通过 JavaScript "merge"两个 HTML 标签