CSS-Grid:如何在不缩小项目本身的情况下使内容居中?

cod*_*leb 7 html css layout css3 css-grid

使用CSS-Grid,我尝试将项目放在网格单元的中心,而不是将它们完全缩小到仅内容。这可能吗?

我在stackblitz上做了一个简单的例子。您会看到那里的项目没有用背景色填充整个网格单元。使该功能正常工作的正确方法是什么?我可以删除justify-items / align-items类,但是内容不再居中。

https://stackblitz.com/edit/angular-8bggtq?file=app/app.component.html

单元格已填充,但内容不在中心:

在此处输入图片说明

单元格未填充,但内容居中:

在此处输入图片说明

.wrapper {
  display: grid;
  height: 100vh;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  justify-items: center;
  align-items: center;
}

.item {
  //justify-self: stretch;
  //align-self: stretch;
}

.one {
  background: red;
}

.two {
  background: pink;
}

.three {
  background: violet;
}

.four {
  background: yellow;
}

.five {
  background: brown;
}

.six {
  background: green;
}

html,
body {
  margin: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
  <div class="item one">1</div>
  <div class="item two">2</div>
  <div class="item three">3</div>
  <div class="item four">4</div>
  <div class="item five">5</div>
  <div class="item six">6</div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 5

网格容器的HTML结构具有三个级别:

  • 容器
  • 项目(容器的子
  • 内容(容器的孙代和项目的子代)

您遇到的问题是您采用的是两级方法,而不是正确的三级方法。当您设置align-itemsjustify-items在容器上,它们适用于电网项目,不适用于内容

这就是您所看到的:网格项在垂直和水平方向上居中。

如果要使网格项目子项(内容)居中,则需要在项目上指定它。您可以在项目上重复您在容器上所做的操作:

.item {
  display: grid;
  justify-items: center;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不需要这些项目中的网格布局,则这是另一种简单的方法:

.item {
  display: flex;
  justify-content: center;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)

以上概念也适用于flex容器。

有关更完整的说明和其他居中方法,请参阅此文章:CSS Grid中居中

.item {
  display: grid;
  justify-items: center;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)
.item {
  display: flex;
  justify-content: center;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)