垂直居中在项目中有广泛应用,而且在各个公司面试中貌似被问到的情况也比较多,这里总结了一些常用的方法以及一些比较奇特的办法来实现。
注意:
如果 .parent 的 height 不写,你只需要 padding: 10px 0; 就能将 .child 垂直居中; 如果 .parent 的 height 写死了,就很难把 .child 居中,以下是垂直居中的方法。 忠告:能不写 height 就千万别写 height。
先设置下基础样式
section {
width: 300px;
height: 300px;
background: #03A9F4;
}
.block {
width: 50px;
height: 50px;
color: #fff;
background: #FFCA28;
}
1、flex法
flex法是比较常用的布局方法,可以设置justify-content和align-items轻松实现水平以及垂直居中,而且不用在意父元素和子元素的高度。
<section class="s1">
<div class="block"></div>
</section>
<style>
.s1 {
display: flex;
justify-content: center;
align-items: center;
}
</style>
2、table-cell
设置display: table-cell,相当于是表格的td,单元格所包含的内联元素可以实现垂直居中。
<section class="s2">
<div class="cell">
<div class="block"></div>
</div>
</section>
<style>
.s2 .cell {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.s2 .block {
display: inline-block;
text-align: center;
}
</style>
3、子元素绝对定位
子元素相对于父元素绝对定位,再将子元素位置适当调整,两种调整方式:
- 负margin,适用子元素宽高已知情况
- translate变换,可以调整未知大小的块
<section class="s3">
<div class="block"></div>
</section>
<style>
.s3 {
position: relative;
}
.s3 .block {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/*margin-top: -25px;
margin-left: -25px; */
}
</style>
4、line-height
line-height可以改变行高,可以使内联元素居中,需要已知父元素的高度
<section class="s4">
<div class="block"></div>
</section>
<style>
.s4 {
line-height: 300px;
text-align: center;
}
.s4 .block {
display: inline-block;
}
</style>
5、动态计算
基本思路是子元素相对父级绝对定位,根据父元素宽高和自身大小改变left和top值。 这里可以使用calc()方法,但需要已知子元素宽高。 如果子元素大小不确定,可以使用JS来改变位置。
<style>
.s5 {
position: relative;
}
.s5 .block {
position: absolute;
left: calc(50% - 25px);
top: calc(50% - 25px);
}
</style>
6、使用margin居中
这个不多说了
<style>
.s6 {
position: relative;
}
.s6 .block {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
下面的实现方法,相对来说不那么常规
7、内联元素实现居中
这种方法需要多加一个内联元素,让它的高度和父级元素的高度一致,再通过vertical-align: middle来实现。
<section class="s7">
<i></i>
<div class="block"></div>
</section>
<style>
.s7 {
text-align: center;
font-size: 0;
}
.s7 i {
display: inline-block;
width: 1px;
height: 100%;
vertical-align: middle;
}
.s7 .block {
display: inline-block;
vertical-align: middle;
}
</style>
8、利用缩放
本质上是改变了元素的大小,因为transform-origin默认在50% 50%,所以看起来就是居中的效果了
<style>
.s8 .block {
width: 100%;
height: 100%;
transform: scale(.18);
}
</style>
9、absolute margin auto
<style>
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
width: 300px;
height: 200px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>