面试高频题之如何实现水平垂直居中?

262 阅读3分钟

前言

大家好,我是3Katrina,最近在准备面试,目前面了有4,5场了,发现有个问题面试中经常被提问到:请问如何实现水平垂直居中,这看起来是一道CSS简单题,但是如果你只是简单回答的话,可能达不到面试官的优异的要求,这篇文章全面解析这道常考八股,让你能够在面试官面前show一波!

分情况回答

首先咱们在回答前,脑子的逻辑一定要清晰,要分点详述水平垂直居中,对每种情况下,有哪些实现水平/垂直居中的方案,下面我也会模拟面试者的角度回答:

单行文本、inline或inline-block 元素

在上述的情况下,实现水平居中有这种常用方式:

text-align

将text-align属性设置为center,可以实现水平居中,

.container {
  text-align: center;
}

垂直居中有两种常用的方式

1.padding

通过设置相等的上下padding实现垂直居中

.container {
  padding: 20px 0;
}

2.line-height

设置line-height等于容器高度实现垂直居中

.container {
  height: 60px;
  line-height: 60px;
}

固定宽高块级盒子水平垂直居中

在这种情况下,有三种方式可以帮我们实现

1.absolute + -margin

使用绝对定位配合负margin

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -31.5px; /* 高度的一半 */
  margin-left: -50px; /* 宽度的一半 */
  width: 100px;
  height: 63px;
}

2. absolute + margin:auto

绝对定位配合margin auto

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 100px;
  height: 63px;
}

3. absolute + calc

使用calc计算偏移量,这个方式性能较差

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: calc(50% - 31.5px);
  left: calc(50% - 50px);
  width: 100px;
  height: 63px;
}

不固定宽高块级盒子水平垂直居中

在这种情况下,有六种方式

1.absolute + transform

使用transform进行偏移

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

2.line-height + vertical-align

结合行高和垂直对齐

.parent {
  height: 300px;
  line-height: 300px;
  text-align: center;
}
.child {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}

3.writing-mode

使用文字方向属性

.parent {
  writing-mode: vertical-lr;
  text-align: center;
}
.child {
  writing-mode: horizontal-tb;
  display: inline-block;
  vertical-align: middle;
}

4.table-cell

模拟表格布局

.parent {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  width: 300px;
  height: 300px;
}
.child {
  display: inline-block;
}

5.flex

弹性盒子布局

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

6. grid

网格布局

.parent {
  display: grid;
  place-items: center;
  height: 300px;
}

总结

通过上面的回答,此时你已经将“如何实现水平垂直居中?”这一问题回答得非常nice了,在大厂的面试中,这份回答可以为你展现自己对css的这方面知识理解的广阔程度,另一方面,能够帮你拖长面试时间,撑住面试的“死亡25分钟”!!!