55种常见垂直居中方式

4次阅读

共计 1405 个字符,预计需要花费 4 分钟才能阅读完成。

css 渣渣,如有错误欢迎指正。

1

.parent {
  height: 400px;
  background: cyan;
  line-height: 400px;
}
.child {
  width: 100px;
  height: 100px;
  background: black;
  display: inline-block;
  vertical-align: middle;
}

父元素设置 line-heightheight相同,使基线在中间,然后子元素设置 vertical-align: middle 使该元素基线与父元素基线重合,达到垂直居中。

2

.parent {
  height: 400px;
  position: relative;
  background: cyan;
}
.child {
  position: absolute;
  width: 100px;
  height: 100px;
  background: black;
  top: 50%;
  margin-top: -50px; /* (height + padding) / 2*/
} 

使用 top、left 偏移了父对象的 50% 宽度高度,然后需要利用 margin 反向偏移居中块的 50% 宽高。
注意 margin 值的设置不能使用百分比,因为 margin 是基于父元素的宽度来计算百分比的。

2.5

.parent {
  height: 400px;
  position: relative;
  background: cyan;
}
.child {
  position: absolute;
  width: 100px;
  height: 100px;
  background: black;
  top: 50%;
  transform: translateY(-50%);
}

与上面的例子原理相同,这里是使用 transform 来做反向偏移。

3

.parent {
  height: 400px;
  background: cyan;
  display: table-cell;
  vertical-align: middle;
}
.child {
  width: 100px;
  height: 100px;
  background: black;
}

table-cell 会被其他一些 css 属性破坏,例如 float,position:absolute,可以考虑增加一个父 div 定义 float 等属性,对 margin 值无反应,响应 padding 属性。

4

.parent {
  height: 400px;
  background: cyan;
  display: flex;
  align-items: center;
}
.child {
  width: 100px;
  height: 100px;
  background: black;
}

这个方法只能在现代浏览器上有效,IE10+、chrome、Safari、Firefox。

5

.parent {
  position: relative;
  width: 100%;
  height: 400px;
  background: cyan;
}
.child {
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100px;
  height: 100px;
  background: black;
}

当一个绝对定位元素,其对立定位方向属性同时有具体定位数值的时候,流体特性就发生了。
具有流体特性绝对定位元素的 margin:auto 的填充规则和普通流体元素一模一样:

  1. 如果一侧定值,一侧 autoauto 为剩余空间大小
  2. 如果两侧均是auto, 则平分剩余空间
正文完
 0