html - CSS-Grid:如何在不缩小元素本身的情况下将内容居中?

标签 html css layout css-grid

<分区>

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

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

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

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

enter image description here

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

enter image description here

.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;
}
<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>

最佳答案

网格容器的 HTML 结构有三个层次:

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

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

这正是您所看到的:网格元素垂直和水平居中。

如果你想将网格元素子项(内容)居中,你需要在元素上指定。您可以对元素重复您对容器所做的操作:

.item {
  display: grid;
  justify-items: center;
  align-items: center;
}

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

.item {
  display: flex;
  justify-content: center;
  align-items: center;
}

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

有关更完整的解释和其他居中方法,请参阅此帖子:Centering in CSS Grid

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

.item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.one   { background: red;   }
.two   { background: pink;  }
.three { background: violet; }
.four  { background: yellow; }
.five  { background: brown; }
.six   { background: green; }
body   { margin: 0; }
<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>

关于html - CSS-Grid:如何在不缩小元素本身的情况下将内容居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48840845/

相关文章:

html - hr内容显示问号

javascript - 这是在单击按钮时将表格行更改为表单的最佳方法吗?

jquery - 为什么在 jQuery 中调整顶部不起作用?

c# - Windows 窗体布局引擎

Qt:在设计器中禁用布局镜像?

android - 如何创建 EditText 仅在 android 中接受字母?

android - 从 Assets 文件夹加载 CSS JS

html - 表 :tr and gradient not working

html - 打印字体的屏幕

android - <p> 样式不正确,除非应用了背景颜色