元素居中

31 阅读1分钟

水平居中

margin: 0 auto(块级元素)

适用于:固定宽度的块级元素

.box {
  width: 200px;
  margin: 0 auto;
}

text-align: center(行内元素/行内块元素)

父元素设置:

.parent {
  text-align: center;
}

子元素是:

  • inline(span, a)
  • inline-block(img, button)
  • inline-flex

都可以居中。

flex + justify-content

最通用:

.parent {
  display: flex;
  justify-content: center;
}

垂直居中

line-height(单行文本)

.text {
  height: 50px;
  line-height: 50px;
}

适用于单行文字

flex + align-items

.parent {
  display: flex;
  align-items: center;
}

absolute + transform(万能法)

.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

水平+垂直同时居中

Flex(最推荐)

万能易用:

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

absolute + transform(经典)

适用于任何情况:

.parent {
  position: relative;
}

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

CSS Grid(最简单的方法)

.parent {
  display: grid;
  place-items: center; /* 完美居中 */
}

text-align + line-height(单行文本专用)

.parent {
  text-align: center;
  line-height: 100px;
  height: 100px;
}