【CSS】HTML中实现元素垂直居中的方法

HTML中实现元素垂直居中常用的3种方法汇总

日常项目中经常会遇到要求某一元素在父元素种垂直居中,实现的效果:
在这里插入图片描述
初始HTML和css部分:

<!-- 父元素 -->
<div class="parentBox">
  <!-- 子元素 -->
  <div class="childenBox">
  </div>
</div>

<!-- css -->
<style>
.parentBox {
      
      
  width: 800px;
  height: 500px;
  background: #ccc;
}
.childenBox {
      
      
  width: 200px;
  height: 200px;
  background-color: #ff0000;
  color: #fff;
}
</style>

以下将介绍css实现垂直居中最常用的3种方法:

一、利用line-height属性来实现

  1. 父级元素设置line-height属性的值等于父级元素的高度,并且给text-align属性的值设置为center;
  2. 将子级元素设置行内块元素,控制vertical-align属性来控制是否居中;
<!-- css -->
<style>
.parentBox {
      
      
  width: 800px;
  height: 500px;
  background: #ccc;
  text-align: center;  /* 水平居中 */
  line-height: 500px;  /* 行高等于高度的值 */
}
.childenBox {
      
      
  width: 200px;
  height: 200px;
  background-color: #ff0000;
  color: #fff;
  display: inline-block;  /* 设置为行内块元素 */
  vertical-align: middle;  /* 行内居中 */
}
</style>

二、利用position定位来实现

  1. 给父级元素设置相对定位position: relative;
  2. 给子级元素设置绝对定位position: absolute;
  3. 给子级元素top和left值50%,margin-left和margin-top各给子级元素宽和高的负的一半(注意:这个地方之所以这样给,是因为定位的元素的left和top值是根据元素左上角来作为基准点,同理right和bottom是根据元素右下角来作为基准点,top:50%后左上角那个点相对于父级元素已经在最中间,但是加上子级元素本身的高度,子级元素相对于父级元素是偏下了一个子级元素的高度,所以需要向上移动其高度一半的距离,同理left也是一样);
<!-- css -->
<style>
.parentBox {
      
      
  width: 800px;
  height: 500px;
  background: #ccc;
  position: relative;  /* 父级元素相对定位 */
}
.childenBox {
      
      
  width: 200px;
  height: 200px;
  background-color: #ff0000;
  color: #fff;
  position: absolute;  /* 子级元素绝对定位 */
  left: 50%;
  top: 50%;
  margin-left: -100px;  /* 负宽度的一半 */
  margin-top: -100px;  /* 负高度的一半 */
}
</style>

三、利用flex布局来实现

给父元素设置flex布局,通过align-items和justify-content属性来控制子元素的水平垂直居中

<!-- css -->
<style>
.parentBox {
      
      
  width: 800px;
  height: 500px;
  background: #ccc;
  display: flex;  /* 设置flex布局 */
  align-items: center;  /* 直接子元素垂直居中 */
  justify-content: center;  /* 直接子元素水平居中 */
}
.childenBox {
      
      
  width: 200px;
  height: 200px;
  background-color: #ff0000;
  color: #fff;
}
</style>

以上是个人经验,希望对大家有所帮助!

猜你喜欢

转载自blog.csdn.net/weixin_44490021/article/details/132042505