H5页面中如何让一个元素垂直居中

2,583 阅读2分钟

1. 单行文本:将其父元素的line-height和height设置成相同的值

#father{
  background-color: rgba(255, 0, 122, 0.3);
  height: 200px;
  line-height: 200px;
}
<div id="father">
    这是一个示例
</div>

2. 使用绝对定位和负外边距(居中元素的高度得是一个具体的数值)

 #father{
  background-color: rgba(255, 0, 122, 0.3);
  width:200px;
  height: 200px;
  position: relative;
}
#child{
  background-color:rgba(20, 30, 50, 0.5);
  width:200px;
  height: 30px;
  position: absolute;
  top:50%;
  margin-top:-15px;
}
    
  <div id="father">
      <div id="child"></div>
  </div>

alt

3. 上一个方法的升级版本:对于宽高未知的元素,可以使用translate,因为translate是相对于自身的尺寸进行偏移的

#father {
  background-color: rgba(255, 0, 122, 0.3);
  width: 200px;
  height: 200px;
  position: relative;
}

#child {
  background-color: rgba(20, 30, 50, 0.5);
  position: absolute;
  top:50%;
  transform: translateY(-50%);
}
<div id="father">
  <div id="child">撑开子元素的高度</div>
</div>
    

4. 绝对定位+ margin:auto

核心:把需要垂直居中的元素相对于父元素进行绝对定位后,将其top和bottom的值设置为相同的值,最后还要设置margin:auto

#father {
  background-color: rgba(255, 0, 122, 0.3);
  width: 200px;
  height: 200px;
  position: relative;
}

#child {
  background-color: rgba(20, 30, 50, 0.5);
  position: absolute;
  width:50px;
  height: 50px;
  top:0;
  bottom:0;
  margin:auto;
}
<div id="father">
  <div id="child"></div>
</div>

5. 使用padding实现子元素的垂直居中

核心:给父元素设置相等的上下内边距,父元素不能设置高度,要让他自动被填充起来

 #father {
  background-color: rgba(255, 0, 122, 0.3);
  width: 200px;
  /* height: 200px; */
  padding:50px 0;
}

#child {
  background-color: rgba(20, 30, 50, 0.5);
  width:50px;
  height: 50px;
}

<div id="father">
  <div id="child"></div>
</div>

6. flex布局

#father {
  background-color: rgba(255, 0, 122, 0.3);
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
}
或者
#father {
  background-color: rgba(255, 0, 122, 0.3);
  width: 200px;
  height: 200px;
  display: flex;
  flex-flow: column;/*改变主轴方向为*/
  justify-content: center;
}

#child {
  background-color: rgba(20, 30, 50, 0.5);
  width:50px;
  height: 50px;
}