css 水平居中垂直居中的几种方法

时间:2022-02-09 15:39:32
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>水平居中垂直居中方法</title>
<style>
div{
width: 200px;
height: 200px;
background: pink;
}
/*第一种方法*/
.box1{
display: table-cell;
vertical-align: middle;
text-align: center;
}
/*第二种方法*/
.box2{
display: flex;
justify-content:center;
align-items:Center;
}
/*第三种方法*/
.box3 span{
width: 200px;
height: 200px;;
background: pink;
overflow: auto;
margin: auto;
position: absolute;
top: ; left: ; bottom: ; right: ;
}
/*第四种方法*/
.box4 span{
position: absolute;
top:%;
left:%;
width:%;
transform:translate(-%,-%);
text-align: center;
}
/*第五种方法*/
.box5 {
display: flex;
text-align: center;
}
.box5 span{
margin: auto;
}
/*第六种方法*/
.box6{
text-align:center;
font-size:;
}
.box6 span{
vertical-align:middle;
display:inline-block;
font-size:16px;
}
.box6:after{
content:'';
width:;
height:%;
display:inline-block;
vertical-align:middle;
}
/*第七种方法*/
.box7{
display: -webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
-webkit-box-orient: vertical;
text-align: center
}
</style>
</head>
<body>
<div class="box1">
<span>垂直居中</span>
</div>
<hr>
<div class="box2">
<span>垂直居中2</span>
</div>
<hr>
<div class="box3">
<span>垂直居中3</span>
</div>
<hr>
<div class="box4" style="position: relative;">
<span>垂直居中4</span>
</div>
<hr>
<div class="box5">
<span>垂直居中5</span>
</div>
<hr>
<div class="box6">
<span>垂直居中6</span>
</div>
<hr>
<div class="box7">
<span>垂直居中7</span>
</div>
</body>
</html>