CSS实现垂直居中的4种思路详解

2020-04-30 15:24:58易采站长站整理

<img class="child" src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/img1.gif" width="50%" alt="test">
</div>

这里写图片描述

【3】通过新增元素来实现垂直居中的效果

新增元素设置高度为父级高度,宽度为0,且同样设置垂直居中vertical- align:middle的inline-block元素。由于两个元素之间空白被解析,所以需要在父级设置font-size:0,在子级再将 font-size设置为所需值;若结构要求不严格,则可以将两个元素一行显示,则不需要设置font-size:0。


<style>
.parent{
height: 100px;
font-size: 0;
}
.child{
display: inline-block;
font-size: 20px;
vertical-align: middle;
}
.childSbling{
display: inline-block;
height: 100%;
vertical-align: middle;
}
</style>
<div class="parent" style="background-color: lightgray; width:200px;">
<div class="child" style="background-color: lightblue;">我是比较长的比较长的多行文字</div>
<i class="childSbling"></i>
</div>

 

思路三:通过绝对定位实现垂直居中

【1】若子元素不定高, 使用top50%配合translateY(-50%)可实现居中效果。
 

translate函数的百分比是相对于自身高度的,所以top:50%配合translateY(-50%)可实现居中效果。

[注意] IE9-浏览器不支持;

[注意]若子元素的高度已知,translate()函数也可替换为margin-top: 负的高度值。


<style>
.parent{
position:relative;
}
.child{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
<div class="parent" style="background-color: lightgray; height:100px;">
<div class="child" style="background-color: lightblue;">测试文字</div>
</div>

【2】若子元素定高,结合绝对定位的盒模型属性,实现居中效果


<style>
.parent{
position: relative;
}
.child{
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
height: 50px;
}
</style>
<div class="parent" style="background-color: lightgray; height:100px;">
<div class="child" style="background-color: lightblue;">测试文字</div>
</div>