CSS 网格不受 padding-bottom 影响

CSS grid not affected by padding-bottom

我正在使用 CSS 网格通过网格自动行将动态数量的元素定位到行中。

然而,不管对网格容器应用了任何填充,最后一个元素始终位于页面底部(填充应用于顶部、左侧和右侧,但不应用于底部)。

有人知道我错在哪里吗?

https://codepen.io/wrgt1/pen/XWjEwXX

#container {
  position: relative;
  width: 100%;
}

.grid {
  width: 100%;
  display: grid;
  grid-auto-flow: row;
  grid-auto-rows: 25%;
  grid-template-columns: 1fr 1fr;
  padding: 50px;
}

.item {
  width: 250px;
  height: 250px;
  background: red;
}
<div id="container">
  <div class="grid">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

有时填充在 HTML 中不起作用,所以在这种情况下,您可以制作 div 或使用 br 标签。

<div class="spacing" style="padding-bottom: 100px;"> 
// or do br where you want it.
<br>

这是因为您的网格高度小于其内容。添加 height 到您的网格和 margin-bottom 而不是填充。希望这可能有所帮助

.grid {
width: 100%;
display: grid;
grid-auto-flow: row;
grid-auto-rows: 25%;
grid-template-columns: 1fr 1fr;
padding: 50px;
height: 100%;
margin-bottom: 50px;
overflow-y: scroll;
}

实际上,(就像@Shristi 提到的)问题的发生是因为网格容器没有到达项目的底部。这是因为 grid-auto-rows 设置为 25%。在第四行之后,这填充了 100%,其他所有内容都从容器中移出。所以你应该改变你的代码如下:

.grid {
  // box-sizing: border-box;
  width: 100%;
  display: grid;
  grid-auto-flow: row;
  grid-auto-rows: 250px; // change this!
  grid-template-columns: 1fr 1fr;
  grid-gap: 50px; // use this for the spacing in between
  padding: 50px; // use this for the spacing top, bottom, left and right of the grid
}

工作示例:here