前端面试中经常会问到元素的垂直居中问题,今天我把自己总结的方法写一下,希望可以帮到大家。
一、父元素宽高未知,子元素宽高未知
样式部分
父元素未知宽高,.other样式是为了填充父元素,模拟父元素不固定的宽高。
.parent{
position: relative;
background-color: red;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: pink;
}
.other{
width: 300px;
height: 300px;
}
html部分
<div class="parent">
<div class="child">
<p>
hello world hello world hello world hello world hello world
hello world hello world hello world hello world hello world
hello world hello world hello world hello world hello world
</p>
</div>
<div class="other"></div>
</div>
二、父元素宽高已知,子元素宽高未知
代码和上边差别不大
css
.parent{
width: 500px;
height: 500px;
position: relative;
background-color: red;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: pink;
}
html
<div class="parent">
<div class="child">
<p>hello world hello world hello world hello world hello world
hello world hello world hello world hello world hello world
hello world hello world hello world hello world hello world</p>
</div>
</div>
当父元素已知宽高时,可以使用margin来定位子元素,子元素浮动(float)或position:absolute。
.child{
float:left;
margin-top:250px;
margin-left:250px;
transform: translate(-50%,-50%);
background-color: pink;
}
三、不管父元素宽高是否已知,子元素宽高未知
以上方法依然适用,本文只是细分了一下。
1. flex
.parent{
width: 500px;
height: 500px;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
background-color: red;
}
.child{
width: 200px;
height: 200px;
background-color: pink;
}
<div class="parent">
<div class="child">
<p>hello world</p>
<p>hello world</p>
<p>hello world</p>
<p>hello world</p>
</div>
</div>
2.使用一个空标签span设置他的vertical-align基准线为中间,并且让他为inline-block,宽度为0
.parent{
height:300px;
width: 300px;
text-align: center;
background: #FD0C70;
}
.parent span{
display: inline-block;;
width: 0;
height: 100%;
vertical-align: middle;
}
.parent .child{
display: inline-block;
color: #fff;
}
<div class="parent">
<span></span>
<div class="child">hello world</div>
</div>