# 如何实现一个元素的水平垂直居中

Issue

欢迎在 Issue 中交流与讨论: Issue 10 (opens new window)

提供一个较少提过的方法,使用 grid,它是做二维布局的,但是只有一个子元素时,一维布局与二维布局就一样了。结合 justify-content/justify-itemsalign-content/align-items 就有四种方案

效果可以见 codepen (opens new window)

.container {
  display: grid;
  justify-content: center;
  align-content: center;
}
.container {
  display: grid;
  justify-content: center;
  align-items: center;
}
.container {
  display: grid;
  justify-items: center;
  align-content: center;
}
.container {
  display: grid;
  justify-items: center;
  align-items: center;
}
Last Updated: 1/17/2021, 2:02:56 PM