【问题标题】:How to collapse the width of CSS-grid to center it in the grid-container如何折叠 CSS-grid 的宽度以使其在网格容器中居中
【发布时间】:2018-08-17 02:44:41
【问题描述】:

是否可以将具有自动填充列的 CSS 网格的宽度折叠到相对于网格容器居中的等宽列所需的最小宽度?

IE 如果我有这样定义的网格:

grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));

并且网格容器是 800px 宽,有没有办法确保网格本身只有 600px 宽而不是 800px?

由于我不确定如何正确解释它,我做了一个小提琴:https://jsfiddle.net/mhozx4ns/10/

我正在寻找一种方法,如果顶部容器的宽度超过将所有子项排成一行所需的宽度,则它的行为类似于底部容器。

body {
  width: 800px;
  background: black;
}

.grid div {
  height: 50px;
  background: #ededed;
}

.css {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  grid-column-gap: 64px;
  grid-row-gap: 64px;
  background: red;
}

.manual {
  width: 664px;
  margin: 32px auto 0;
  background: blue;
}

.manual:after {
  content: '';
  display: table;
  width: 100%;
}

.manual.grid div {
  width: 300px;
  float: left;
  margin-bottom: 64px;
}

.manual.grid div:nth-of-type(even) {
  margin-left: 64px;
}

.manual.grid div:last-child {
  margin-bottom: 0;
}


}
<div class="css grid">
  <div>

  </div>
  <div>

  </div>
  <div>

  </div>
</div>

<div class="manual grid">
  <div>

  </div>
  <div>

  </div>
  <div>

  </div>
</div>

【问题讨论】:

    标签: css centering css-grid


    【解决方案1】:

    当您在规则中说 minmax(300px, 1fr) 时,您是在说:

    每列的最小宽度必须为 300 像素,最大宽度必须为 1fr

    fr 单元占用网格容器中的可用空间。因此,如果您的容器是 800 像素宽,fr 将考虑所有空间。

    此外,由于fr 消耗了所有可用空间,因此通过分配可用空间来发挥作用的justify-content 变得无用。

    为什么不直接删除1fr

    body {
      width: 800px;
      background: black;
    }
    
    .css {
      display: grid;
      justify-content: center;
      grid-template-columns: repeat(auto-fill, 300px);
      grid-auto-rows: 50px;
      grid-column-gap: 64px;
      grid-row-gap: 64px;
      background: red;
    }
    
    .grid div {
      background: #ededed;
    }
    <div class="css grid">
      <div></div>
      <div></div>
      <div></div>
    </div>

    【讨论】:

    • 如果有足够的元素填充第一行,则为列提供固定宽度有效。如果我有足够的空间放置 3 个但只有 2 个元素可以放置,它们将左对齐而不是居中。
    • 也可以尝试将justify-items: center 添加到网格容器中。
    • 这似乎没有任何改变。不在小提琴或我的实际用例中。
    • 我明白了,使用自动调整而不是自动填充以及元素的固定宽度可以创建所需的效果。 grid-template-columns: repeat(auto-fit, 300px);
    猜你喜欢
    • 1970-01-01
    • 2021-01-03
    • 2020-08-12
    • 2020-07-31
    • 2019-10-26
    • 2019-09-26
    • 2014-03-09
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多