垂直居中(待更新)

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

综述

<!-- 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;

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

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

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

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

#container {
  width: 100%;
  height: 400px;
  /* */
  position: relative;
}

#box {
  width: 100px;
  height: 100px;
  background: yellow;
  /* */
  position: absolute;
  top: 50%;
  margin-top: -50px;
}

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

#container {
  width: 100%;
  height: 400px;
  /* */
  position: relative;
}

#box {
  width: 100px;
  height: 100px;
  background: yellow;
  /* */
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
}

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

#container {
  width: 100%;
  height: 400px;
  /* */
  position: relative;
}

#box {
  width: 100px;
  height: 30%;
  background: yellow;
  /* */
  position: absolute;
  top: 50%;
  margin-top: -15%; /* 这里的百分比是基于父元素的 width,不是基于 height,故不可用 */
}

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

#container {
  width: 100%;
  height: 400px;
  /* */
  position: relative;
}

#box {
  width: 100px;
  height: 100px;
  background: yellow;
  /* */
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto 0;
}

方法 6:设置第三方基准

<!-- html -->
<div id="container">
  <div id="base"></div>
  <div id="box"></div>
</div>
#container {
  width: 100%;
  height: 400px;
}

#box {
  width: 100px;
  height: 100px;
  background: yellow;
  /* */
  margin-top: -50px;
}

/* */
#base {
  height: 50%;
  background: orange;
}

方法 7:使用 CSS grid

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

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

无设置 height

#container {
  width: 100%;
  height: 400px;
  /* */
  display: grid;
}

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

/* */
.one, .three{
  background: skyblue;
}

box 设置 height,分两种情况:

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

#container {
  width: 100%;
  height: 400px;
  /* */
  display: grid;
  grid-template-rows: 1fr 100px 1fr;
}

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

/* */
.one, .three{
  background: skyblue;
}

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

。。。

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

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

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

参考链接

最后更新于