尝试了网上大多数的垂直居中的方式,将可以实现的大致进行一个整理,只针对块元素。
1、通过将外层标签元素生成的显示框设置为table,在将内层嵌套的标签元素生成的显示框设置为table-cell,通过设置表格单元为垂直对齐vertical-align:middle
<div class="out">
<div class="in"><p>垂直居中的方式</p></div>
</div>
.out{
width: 500px;
height: 500px;
background: #4522ff;
display: table;
}
.in{
width: 50%;
height: 50%;
/*background: #ff0e10;*/
display: table-cell;
vertical-align: middle;
}
这种方式会对浏览器的运行效率有所影响,所以不建议使用。
2、通过绝对布局position: absolute;在设置其top属性设置为页面高度的一半,在将其上部外边距设置为其高度的负的一半margin-top,来实现垂直居中。
<div class="content">垂直居中的方式</div>
.content {
width: 500px;
height: 500px;
background: #4522ff;
position: absolute;
top: 50%;
margin-top: -250px; /* negative half of the height */
}
这种方式优点在于不需要外部标签,但是当页面缩小到出现滚动条时标签将显示不全,可以根据开发场景合理使用。
3、通过使用margin的auto属性来实现垂直居中,将标签设置为绝对定位,对于整个页面的top和button设置为相同的值,外边距margin设置为自适应auto,即可实现垂直分布。
<div class="content">垂直居中的方式</div>
.content {
position: absolute;
background: #4522ff;
top: 0;
bottom: 0;
margin: auto 0px;
height: 250px;
width: 250px;
}
这种垂直居中方式推荐使用。
4、通过将对象作为弹性伸缩盒显示display: flex;在使用其子属性align-self: center;纵轴方向居中对齐来实现垂直居中对齐。
<div class="out">
<div class="in">垂直居中的方式</div>
</div>
.out{
width: 500px;
height: 500px;
background: #4522ff;
/*float: left;
margin-bottom: -120px;*/
display: flex;
}
.in{
width: 250px;
height: 250px;
background: #ff0e10;
align-self: center;
}
这种方法也是目前最通用的。
5、第五种方法和第二种方法类似,但需要嵌套元素,也是通过绝对布局来实现垂直居中的。
<div class="out">
<div class="in">垂直居中的方式</div>
</div>
.out{
width: 500px;
height: 500px;
background: #4522ff;
position: relative;
}
.in{
width: 250px;
height: 250px;
background: #ff0e10;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
目前找到可用的方法就这些,后面如果发现会进行补充。