[css] 几种垂直居中方法的总结

最近总结了一下元素垂直居中的几种比较方便的,无需计算的方法,记录一下!

一、line-height居中单行文本

line-height: <你所需要的高度>

二、line-heightdisplay:inline-block 实现多行居中

CSS代码:

.father{
  width: <你所需要的宽度>;
  line-height: <你所需要的高度>;
}

 .son{
   display: inline-block;
   line-height: <你所需要的内容的行高>;
 }

HTML代码:

<div class="father">
  <span class="son">
    你所需要的内容
  </span>
</div>

三、table布局居中多行文本

.father{  
    // 父容器
    display: table;
    vertical-align: middle;
    }

.son{
    // 需要居中的子元素
    display: table-cell;
    vertical-align: middle;
}

四、 flex布局

{
    display: flex;
    align-items: center
}

五、使用transform: translateY(-50%);

这个是最近才知道的方法,感觉很方便很实用,强烈推荐

{
    top: 50%;
    transform: translateY(-50%);
}

首先,使用这个方法无需知道容器的高度,所以使用起来超级方便
以下是需要注意的点:

  • 一定是top: 50%; 而不是margin-top: 50%;top是根据容器的高度来计算移动的距离,而margin-top是根据容器的宽度来计算移动的距离
  • 如果position为默认的static,那么这个css是无法起到效果的

总结:使用什么方法,还是看哪种方法最方便,没有什么最好的方法

猜你喜欢

转载自blog.csdn.net/AdamAndTina/article/details/79418813