CSS 水平垂直居中

96 阅读1分钟

1. 最简单的方式:flex + margin: auto

.parent {
  display: flex;
}

.child {
  margin: auto;
}

在FFC(Flex格式上下文)中,设置子元素 margin: auto 任何空余空间都会被自动分配到该方向的 margin 中,因此上述样式将实现水平垂直居中的效果。

另外通过设置子元素样式可以实现其他效果:

margin-left: auto; // 靠右
margin-top: auto; // 靠底
margin: auto xxx; // 垂直居中
align-self: center; // 垂直居中

2. 设置父元素的flex

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

这种也是用的比较多的。

3. 绝对定位 + margin: auto

.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

由于 margin: auto 具有自动填充闲置空间的作用,而子元素被设置为占满父元素,则水平垂直方向上的剩余空间将被 margin: auto 填充。

4. 绝对定位 + transform

.parent {
  position: relative;
}

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

注意 translate(-50%, -50%) 是基于自身宽高的百分比。