【问题标题】:CSS grid not affected by padding-bottomCSS 网格不受 padding-bottom 影响
【发布时间】:2021-01-04 11:42:40
【问题描述】:

我正在使用 CSS 网格将动态数量的元素定位到使用 grid-auto-rows 的行中。

然而,最后一个元素总是放在页面底部,而不管网格容器是否有任何填充(填充应用于顶部、左侧和右侧,但不应用于底部)。

有人知道我哪里出错了吗?

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>

【问题讨论】:

  • 这是 chrome 问题
  • 不幸的是,我在 Chrome 和 Safari 中遇到了同样的问题@TemaniAfif
  • 是的所有 webkit 浏览器

标签: html css css-grid grid-layout


【解决方案1】:

实际上,(就像@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

【讨论】:

  • 太好了,非常感谢!这是否意味着不可能对 grid-auto-rows 使用百分比值?
  • 显然你发现了它不起作用的问题:-)
【解决方案2】:

这是因为网格的高度小于其内容。将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;
}

【讨论】:

  • 不幸的是这不起作用,它会导致滚动问题Codepen
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多