垂直和水平居中网格容器

Par*_*edi 6 html css grid css3 css-grid

令人惊讶的是,我无法在网上找到任何相关信息.也许我错过了什么.如何使用CSS Grid水平和垂直地将整个主包装器中心放置,显然,保持响应性?

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

使用上面的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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="maingrid">
  <div class="centerthis">loremloremlorem</div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 11

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

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

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

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

那是因为容器没有额外的高度.行是内容的高度.而不是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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="maingrid">
  <div class="centerthis">loremloremlorem</div>
</div>
Run Code Online (Sandbox Code Playgroud)

更多信息:


小智 7

而不是使用

  align-items: center;
  justify-items: center;
Run Code Online (Sandbox Code Playgroud)

您可以使用

  place-items: center;
Run Code Online (Sandbox Code Playgroud)

  align-items: center;
  justify-items: center;
Run Code Online (Sandbox Code Playgroud)
  place-items: center;
Run Code Online (Sandbox Code Playgroud)