垂直居中一直都是比较麻烦的地方,在这分享集中自己知道的方法
1.方法一
把表格的display设置为表格(table)代码及效果如下
//css部分
.table {
display: table;
vertical-align: middle;
position: absolute;
width: 100%;
height: 100%;
background: pink;
}
.cell {
display: table-cell;
vertical-align: middle;
}
.content {
width: 100%;
height: 100px;
background: red;
text-align:center;
line-height: 100px;
font-size: 80px;
color: white;
}
//
缺陷:在ie下无效,需要嵌套标签
优点:content动态改变高度,不需要设置
2.方法二
使用position:absolute与top,margintop一起实现
.container {
position: absolute;
display: table;
width: 100%;
height: 100%;
background: lightgreen;
}
.box {
position: absolute;
top: 50%;
width: 100%;
height: 100px;
margin-top: -50px;
/* 高度为盒子高度的一般 */
background: lightpink;
}
.content {
width: 100%;
height: 100px;
text-align: center;
line-height: 100px;
font-size: 80px;
color: white;
}
缺陷:当没有足够的高度时content会消失
有点:不需要嵌套,适用于所有浏览
3.方法三
使用absolute然后left0 ,margin:auto直接实现垂直居中
.container {
position: absolute;
width: 100%;
height: 100%;
background: lightgreen;
}
.box{
position: absolute;
top:0;
bottom:0;
left:0;
right:0;
margin: auto;
height: 240px;
width: 70%;
background: pink;
}
缺陷:ie无效(则很难的太惨了),空间不够content被截断。。
有点:简单粗暴!
4.方法四
.container {
position: absolute;
width: 100%;
height: 100%;
background: lightgreen;
}
.box {
width: 50%;
height: 40%;
margin-top: 15%;
/*=container的一般减去box高度的一半再除以二 */
background: pink;
}
缺陷:麻烦,不一定完整
优点:简单
大概就是这样几种方法,布局这方面的东西自己也是不是很上心,毕竟我觉得写逻辑更加重要
布局的实现方法是在是太多了