CSS垂直居中的几种实现方式

308 阅读1分钟

使用绝对定位和负外边距

HTML

<div id="a">
    <div id="b"></div>
  </div>

CSS

#a{
  width:200px;
    height:200px;
  background: black;
  position: relative;
}
#b{
  width:100px;
  height:100px;
  background: red;
  position:absolute;
  top: 50%;
  margin: -50px 0 0 0;
}

缺点:必须提前知道居中块级元素的尺寸。

使用绝对定位transform

HTML

<div id="a">
    <div id="b"></div>
  </div>

CSS

#a{
  width:200px;
    height:200px;
  background: black;
  position: relative;
}
#b{
  width:150px;
    height:150px;
  background: red;
  position:absolute;
  top: 50%;
  transform:translate(0,-50%);
}

好处:这种方法不需要知道居中元素的尺寸

使用flex布局align-items属性

HTML

<div id="a">hello</div>

CSS

#a{
  width:200px;
  height:200px;
  background: black;
  color:red;
  position: relative;
  display:flex;
  align-items:center;
}

flex布局相当好用,基本可以解决任意布局需求,个人用的比较多的布局方式。

使用flex布局中的flex-direction

HTML

<div id="a">
    <div id="b"></div>
  </div>

CSS

#a{
  width:200px;
  height:200px;
  background: black;
  display:flex;
  flex-direction: column;
  justify-content:center
}
#b{
  width:200px;
  height:100px;
  background:red;
}

使用Grid

HTML

<div id="a">
    <div id="b"></div>
    <div id="c">hello</div>
    <div id="d"></div>
  </div>

CSS

#a{
  width:200px;
  height:200px;
  display:grid;
}
#c{
  background:red;
}
#b,#d{
  background:blue;
}

总结:

其实在网上还看到非常多的方法,有十几种方式可以实现垂直居中,比较常用的有三种思路:

  • flex布局
  • 绝对定位+translate或者绝对定位+margin
  • grid布局

知道这些就已经非常足够了。