Author:Vivi
Time:2021-06-04
采用四种方式实习div块级元素垂直水平居中:
①position定位(子绝父相)
②position定位(子绝父相)+transform
③display:table-cell+vertical align:middle
④flexbox弹性盒子 display:flex+justify content:center+align item:center
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.box1 .content1{
width: 100px;
height: 100px;
background-color: greenyellow;
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0px 0px -50px;
}
.box2{
width: 200px;
height: 200px;
background-color: lightblue;
position: relative;
}
.box2 .content2{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.box3{
width: 200px;
height: 200px;
background-color: grey;
position: relative;
display: table-cell;
vertical-align: middle;
}
.box3 .content3{
width: 100px;
height: 100px;
background-color: indianred;
margin-left: auto;
margin-right: auto;
}
.box4 {
width: 200px;
height: 200px;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
}
.box4 .content4 {
width: 100px;
height: 100px;
background-color: burlywood;
}
</style>
</head>
<body>
<p>position</p>
<div class= "box1">
<div class= "content1"></div>
</div>
<p>position+transform</p>
<div class= "box2">
<div class= "content2"></div>
</div>
<p>display:table-cell vertical-align:middle</p>
<div class= "box3">
<div class= "content3"></div>
</div>
<p>flexbox</p>
<div class= "box4">
<div class= "content4"></div>
</div>
</body>
</html>