我可以从中心填充网格容器吗?

Ogn*_*jen 3 html css css-grid

有没有办法从中心填充网格?

我有一个 CSS 网格容器,它具有动态内容(它会更新,因此子项数量不固定),如下所示:

#container { 
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
}
Run Code Online (Sandbox Code Playgroud)

如果我填满了所有 4 列,它将如下所示:

1 2 3 4 //Numbers that represent containers children
Run Code Online (Sandbox Code Playgroud)

这对我来说没问题,但是当我的主容器中只有两个 div 时就会出现问题,然后它看起来像这样:

1 2 0 0
Run Code Online (Sandbox Code Playgroud)

我想实现的是:

0 1 2 0
Run Code Online (Sandbox Code Playgroud)

Muh*_*bar 5

新答案:

如果您只想坚持grid假设您只有四列并且可能的配置是0 1 0 0, 0 1 1 0, 0 1 1 11 1 1 1那么以下 CSS 有效:

.container {
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
}

.col {
  height: 50px;
  background: green;
}

.col:first-child {
  grid-column-start: 2;
}

.col:first-child:nth-last-child(4) {
  grid-column-start: 1;
}
Run Code Online (Sandbox Code Playgroud)

假设你有 HTML:

<div class="container">
  <div class="col">
  Col
  </div>
  <!-- Other Cols Here -->
</div>
Run Code Online (Sandbox Code Playgroud)

工作小提琴

原始答案:

对于网格,不可能将动态数量的元素居中。网格布局适用于元素数量固定的布局。

请参阅网格flex布局的使用。您的问题更适合通过 flex 解决,您可以justify-content: center在 flex 容器上使用以实现居中的孩子。

要实现以孩子为中心,请修改#containerdiv上的样式:

#container { 
  display: flex;
  justify-content: center;
}
Run Code Online (Sandbox Code Playgroud)

您想要0 1 0 00 1 1 0、 的场景0 1 1 11 1 1 1并假设只有四列

.container {
  display: flex;
  justify-content: center;
}

.col {
  width: 25%;
  height: 50px;
  background: green;
}

.col:last-child:not(:nth-child(even)):first-child {
  margin-left: -25%;
}

.col:last-child:not(:nth-child(even)):not(:first-child) {
  margin-right: -25%;
}
Run Code Online (Sandbox Code Playgroud)

我假设您的标记将是这样的:

<div class="container">
  <div class="col">
  Col
  </div>
  <!-- Other Columns Go Here -->
</div>
Run Code Online (Sandbox Code Playgroud)

工作小提琴