html结构
<p class="box box2">
<span class="content content2">垂直居中</span></p>默认css样式结构
.box{
width:200px;
height:200px;
background-color:green;
}
.content{
background-color:yellow;
}1. table-cell
该方法兼容IE8+,火狐,谷歌,并且content是否有宽高都可以。 注:IE8+ 包含 IE8
.box2{
display:table-cell; //此元素会作为一个表格单元格显示(类似 <td> 和 <th>)
text-align:center; //左右居中
vertical-align:middle; //上下居中
}.box2{
display: flex;
justify-content:center; //左右居中
align-items:center; //上下居中
}
3. 绝对定位和负边距
该方法兼容IE8+,火狐,谷歌, content必须有宽高 。
.box2{
position:relative;
}
.content2{
position:absolute;
top:50%;
left:50%;
margin-top:-40px;
margin-left:-40px;
}4. 绝对定位和0
该方法兼容IE8+,火狐,谷歌, content必须有宽高。
.box2{
position:relative;
}
.content2{
margin:auto;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}5. 绝对定位和transform
该方法 不兼容IE8 ,兼容IE9+,火狐,谷歌, content是否有宽高都可以。
.box2{
position:relative;
}
.content2{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}6. display:flex 和 margin:auto
content有宽高: 不兼容IE8,IE9, content没有宽高: 不兼容IE 。有无宽高都 兼容火狐、谷歌。
.box2{
display: flex;
text-align: center;
}
.box2 .content2{margin: auto;}以上就是css实现垂直居中的6种方法(代码示例)的详细内容,更多请关注Gxlcms其它相关文章!
查看更多关于css实现垂直居中的6种方法(代码示例)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did68007