垂直居中(待更新)

如何实现元素的垂直居中?

综述

<!-- html -->
<div id="container">
  <div id="box"></div>
</div>

方法 1:父元素 display:flex; align-items:center;

#container {
  width: 100%;
  height: 400px;
  /* */
  display: flex;
  align-items: center;
}

#box {
  width: 100px;
  height: 100px;
  background: yellow;
}

方法 2:父元素 display:flex; flex-direction: column; justify-content:center;

方法 3:子元素绝对定位,top:50%,margin-top:-(高度/2) ;父元素相对定位。

当 父元素为 relative,子元素为 absolute 时,子元素脱离文档流,不占据原来的位置,浮在了其他元素上面。但是其位置却与父元素 static(默认)中的不同,而是相对于父元素的位置而定位。

方法 4:子元素绝对定位,top:50%,margin-top:-(高度/2),transform: translate(0, -50%); 父元素相对定位。

方法 5:方法 2 的变种。当子元素 height 为百分比时,子元素的 margin 也可以写父元素的百分比。

方法 5:子元素绝对定位,top: 0,bottom: 0,margin:auto 0,(三个要同时生效); 父元素相对定位。

方法 6:设置第三方基准

方法 7:使用 CSS grid

这种场景下使用 Grid Layout 非常方便,只需要设置 .one .three 两个辅助元素即可。

无设置 height

box 设置 height,分两种情况:

  • box 高度为 100 px。此时高度的分配,one 和 three 的高 h (totalHeight - 100) / 3 px; box 和 three 中间有 h 的空缺高度。

方法 8:使用 padding 实现子元素的垂直居中

。。。

方法 9:使用 line-height 对单行文本进行垂直居中

方法 10:使用 line-heightvertical-align 对图片进行垂直居中

方法 11:使用 display: table;vertical-align: middle; 对容器里的文字进行垂直居中

参考链接

最后更新于