设置垂直居中的几种方法

自己知道的不多,所以去网上搜了几种办法,以后了解到了还会继续补充:

(1)table-cell

将div的显示方式设置为表格,利用表格的vertical-align:middle属性:

<div clss="wrapper">
    <div class="cell">
        <div>垂直居中</div>
    </div>
</div>

<style>
   .wrapper {display: table;width: 100px;height: 100px;}
   .cell{display: table-cell;vertical-align: middle:}
</style>

这种方法是将容器用display: table变成一个块级表格,然后用display: table-cell把子元素变成表格单元格,然后就相当于在表格中加vertical-align:middle,就可以实现垂直居中了。

话不多说直接上图看看效果:

PPT中表格如何垂直居中Python ppt中的表格如何垂直居中_垂直居中


(2)display: flex

<style>
   .wrapp{display: flex; justify-content:center; align-items: center;}
</style>

<div class="wrapp">
   <div class="content">垂直居中</div>
</div>

还是上图!

PPT中表格如何垂直居中Python ppt中的表格如何垂直居中_PPT中表格如何垂直居中Python_02


display: flex:是一种布局方式,既适用于块级元素,也适用于行级元素,flex意为“弹性布局”,设置后子元素的float,vertical-align,clear属性将失效。

justify-content:内容对齐,应用在弹性容器上,将弹性容器内的内容按照主轴线对齐:

justify-content: flex-start / flex-end / center / space-between / space-around

align-items:设置了flex容器的对齐方式。

(3)margin:auto和top,left,right,bottom都设置为0

<style>
   .content{ width: 50%;height: 50%;margin: auto;position: absolute;
   top: 0; left: 0; bottom: 0; right: 0;border: 1px solid black;}
</style>
  
<div class="content"></div>

上图!为了效果我把图截大点,边边角角都加上!!

PPT中表格如何垂直居中Python ppt中的表格如何垂直居中_PPT中表格如何垂直居中Python_03

(4)transform:translate(-50%,-50%)

往上移动自己宽度的50%,往左移动自身长度的50%

<style>
   .content{position: absolute;top:50%;left:50%;width:100%;transform:translate(-50%,-50%);
   text-align: center;}
</style>
  
<div class="content">垂直居中</div>

上!

PPT中表格如何垂直居中Python ppt中的表格如何垂直居中_宽高_04


与用margin-left和margin-top居中进行比较:

margin需要知道自身的宽高,而translate是相对于自身宽高的百分比而言,所以不需要知道自身的宽高。

(5)子绝父相

这个是个人之前在用的笨办法,子元素用绝对定位,父级元素用相对定位,可以按照笨办法一点一点挪过去,这里提及一下,草草用个代码解决一下就行了。

<style>
   .father{width: 100px;height: 100px;position: relative;}
   .son{position: absolute;top: 39.5px;left: 18px;}
</style>
  
<div class="father">
   <div class="son">垂直居中</div>
</div>

这样子块就可以在父块中垂直居中

PPT中表格如何垂直居中Python ppt中的表格如何垂直居中_垂直居中_05


(6)display:inline-block

在网上有看到大佬这样写,自己尝试了一下,还真成了,学到了学到了

<style>
   .box{text-align:center;width: 100px;height: 100px;}
   .box span{vertical-align:middle; display:inline-block; font-size:16px;}
   .box:after{content:'';width:0;height:100%;display:inline-block;vertical-align:middle;}
</style>
<div class="box"><span>垂直居中</span></div>

PPT中表格如何垂直居中Python ppt中的表格如何垂直居中_垂直居中_06


:before 和 :after 的主要作用是在元素内容前后加上指定内容,这个方法是通过after来占位,从而实现居中。

(7)line-height

这个也是我自己在用的方法,将行高设置和块级元素一样高就可

<style>
   .box{width: 150px;height: 150px;line-height: 150px;text-align: center;margin: 0 auto;}
</style>

<div class="box">
   <span>垂直居中</span>
</div>

PPT中表格如何垂直居中Python ppt中的表格如何垂直居中_宽高_07

垂直居中的方法还有很多种,上面几种方法有的是我一直在用的,有的是仿照大佬写的,总结下来自己也学到了不少,以后学到了新的垂直居中方法还会继续补充!