小编给大家分享一下css实现垂直居中的方法有哪些,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
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; //上下居中
}
2. display: flex;
该方法不兼容IE8,IE9,content是否有宽高都可以。兼容火狐、谷歌
参考flex布局:https://www.cnblogs.com/qingchunshiguang/p/8011103.html
.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实现垂直居中的方法有哪些有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。