垂直和水平居中网格容器

Center a grid container vertically and horizontally

令人惊讶的是,我在网上找不到任何相关信息。也许我错过了什么。您如何使用 CSS 网格水平和垂直居中整个主包装器,并且显然保持响应能力?

.wrapper {
  display: grid;
  grid-template-columns: minmax(100vw, 1fr);
  grid-template-rows: minmax(100vh, 1fr);
  align-items: center;
  justify-content: center;
}
<div class="wrapper">
  <div class="centerthis">loremloremlorem</div>
</div>

使用上面的 CSS,div 是垂直居中,而不是水平居中。

以下 CSS 将 div 水平居中,但不是垂直居中:

.maingrid {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  align-items: center;
  justify-content: center;
}

.centerthis {
  align-self: center;
  justify-self: center;
}
<div class="maingrid">
  <div class="centerthis">loremloremlorem</div>
</div>

而不是 justify-content: center 使用 justify-items: center.

.wrapper {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 100vh;
  align-items: center;
  justify-items: center; /* adjusted */
}
<div class="wrapper">
  <div class="centerthis">loremloremlorem</div>
</div>

在你的第二个例子中,你说:

The following CSS centers the div horizontally but not vertically.

那是因为容器没有额外的高度。行是内容的高度。而不是 grid-template-rows: 1fr 尝试 grid-template-rows: 100vh.

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

.centerthis {
  align-self: center;
  justify-self: center;
}

body {
  margin: 0;
}
<div class="maingrid">
  <div class="centerthis">loremloremlorem</div>
</div>

更多信息:

如果你这样做更好

.wrapper {
  display: flex;
  flex-direction: row; // Not really necassary though
  justify-content: center; // Or you could use "space-around"
  align-items: center;
}

我建议你使用flex-box,它是CSS3中新的布局模式。

在这种情况下,我们只需给 .maingrid display: flex 一个高度并将内容居中。

然后让 .centerthis 将自己对齐到他父元素的中间,如下所示。

希望对您有所帮助,

.maingrid {
  display: flex;
  height: 100px;
  justify-content: center;
}

.centerthis {
  align-self: center;
}
<div class="maingrid">
  <div class="centerthis">loremloremlorem</div>
</div>

2x2 网格中 4 个项目的示例。

如果你想让外容器内的物品变小;将 width: 100% 更改为您喜欢的任何内容,并在 CSS 中添加 margin-top:margin-left:(例如:width: 70%margin-top: 15%margin-left: 15%。边距是你剩下的一半 space,以保持居中)

#wrapper {
  position: absolute; 
  display: grid;
  width: 100%;
  grid-template-columns: 1fr 1fr;
}
<div id="wrapper">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

而不是使用

  align-items: center;
  justify-items: center;

你可以使用

  place-items: center;

.wrapper {
        display: grid;
        grid-template-columns: 1fr;
        grid-template-rows: 100vh;
        place-items: center;
        border: 2px solid;
       }
<div class="wrapper">
  <div class="centerthis">loremloremlorem</div>
</div>