子盒子水平和垂直居中4种方式
<!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>
.father {
position: relative;
width: 500px;
height: 500px;
background: pink;
}
/* 第一种 */
.son {
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: purple;
}
/* 第二种 */
.son {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: purple;
}
/* 第三种 */
.son {
position: absolute;
top: 50%;
left: 50%;
/* 子盒子水平和垂直居中 */
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: purple;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>