Skip to content

水平垂直居中(至少6种)

1. Flexbox 布局

css
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.item {
  /* 子元素内容 */
}

2. Grid 布局

css
.container {
  display: grid;
  place-items: center;
  height: 100vh;
}

.item {
  /* 子元素内容 */
}

3. 绝对定位 + transform

css
.container {
  position: relative;
  height: 100vh;
}

.item {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

4. 绝对定位 + margin: auto

css
.container {
  position: relative;
  height: 100vh;
}

.item {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 200px;
  height: 200px;
}

5. Table 布局

css
.container {
  display: table;
  width: 100%;
  height: 100vh;
}

.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.item {
  display: inline-block;
  /* 子元素内容 */
}

6. 行内块级元素 + vertical-align

css
.container {
  width: 100%;
  height: 100vh;
  text-align: center;
  font-size: 0;
}

.container::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.item {
  display: inline-block;
  vertical-align: middle;
  font-size: 16px;
  /* 子元素内容 */
}

基于 VitePress 的本地知识库