如何实现一个块级元素的水平垂直居中

167 阅读1分钟

作为一个前端工程师,水平垂直居中问题是最基础的知识点,今天就来整理一下实现水平垂直居中的方法,我这里整理了五种,欢迎大家补充更多想法。

HTML

<div class="box">
    <div class="item"></div>
</div>

CSS

1.已知子元素宽高的情况下,利用绝对定位+margin值分别左移和上移宽高的一半。
.box{
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid red;
}
.item{
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -60px;
  width: 120px;
  height: 100px;
  background: tomato;
}
2.未知元素宽高的情况下,利用绝对定位+transform。
.box{
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid red;
}
.item{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 120px;
  height: 100px;
  background: tomato;
}
3.未知元素宽高下,利用绝对定位+margin:auto。
.box{
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid red;
}
.item{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 120px;
  height: 100px;
  background: tomato;
}
4.未知元素宽高下,利用display:table-cell。
.box{
  display: table-cell;
  vertical-align: middle;;
  width: 400px;
  height: 400px;
  border: 1px solid red;
}
.item{
  margin: 0 auto;
  width: 120px;
  height: 100px;
  background: tomato;
}
5.利用flex(推荐)。
.box{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 400px;
  height: 400px;
  border: 1px solid red;
}
.item{
  width: 120px;
  height: 100px;
  background: tomato;
}

有任何问题欢迎指出并交流哦!