纯CSS3实现垂直居中的九种方法

时间:2023-03-08 18:07:43

浏览时看到的资料,每个都做了测试,很好,就先收了~

测试的是谷歌浏览器,没有任何问题,用360,IE11,火狐,搜狗浏览器做测试时,第五个方法在360,搜狗,和IE11有点问题,第七个在IE11有问题,第8个在IE11,火狐有问题。保险起见,使用前四个好,出现的问题需要再解决。

 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>CSS3实现垂直居中的方法</title>
<style>
.box{
width: 500px;
height: 250px;
border: 1px solid #000000; }
.box1{
display: table-cell;
vertical-align: middle;
text-align: center;
background-color: #A0A0A0;
}
span{
background-color: #e23a6e;
font-size: 18px;
font-weight: 500;
}
.box2{
display: flex;
justify-content: center;
align-items: center;
text-align: center;
background-color: #A44849;
}
.box3{
position: relative;
}
.box3 span{
position: absolute;
width: 300px;
height: 60px;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -30px;
background-color: #F5AA51;
text-align: center;
border: 1px solid #000000;
}
.box4{
position: relative;
}
.box4 span{
width: 50%;
height: 50%;
border: 1px solid blue;
margin: auto;
overflow: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color:#00ff00;
}
.box5{
position: relative;
}
.box5 span{
position: absolute;
top: 50%;
left: 50%;
width: 100%;
transform: translate(-50%,-50%);
text-align: center;
border: 1px solid black;
background-color: #fa96b5;
}
.box6{
text-align: center;
font-size: 0;
}
.box6 span{
vertical-align:middle ;
display: inline-block;
font-size: 16px;
background-color: #ffff00;
}
.box6:after{
content: '';
width: 0;
height: 100%;
display:inline-block;
vertical-align:middle;
}
.box7{
display: flex;
text-align: center;
}
.box7 span{
margin: auto;
background-color: antiquewhite;
}
.box8{
display: -webkit-box;
display: -webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
-webkit-box-orient: vertical;
text-align: center
} .floater {
float:left;
height:50%;
margin-bottom:-25px; }
.content {
border: 1px solid blue;
clear:both;
height:50px;
position:relative;
background-color: aqua;
}
</style>
</head>
<body>
<div class="box box1"><span>方法一:方法1:table-cell.纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box box2"><span>方法二:方法2:display:flex.纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box box3"><span>方法三:方法3:绝对定位和负边距.纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box box4"><span>方法四:方法4:绝对定位和0 .纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box box5"><span>方法五:方法5:translate .纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box box6"><span>方法六:方法6:display:inline-block .纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box box7"><span>方法七:方法7:display:flex和margin:auto .纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box box8"><span>方法八:方法8:display:-webkit-box .纯CSS3实现垂直居中,哈哈哈,我居中了</span></div>
<div class="box">
<div class="floater"></div>
<div class="content">方法九:display:-webkit-box .纯CSS3实现垂直居中,哈哈哈,我居中了 </div>
</div>
</body>
</html>

纯css3实现居中

下面的时测试结果图

纯CSS3实现垂直居中的九种方法