html结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子水平垂直居中</title>
<style>
*{
margin: 0;
padding: 0;
}
.fa{
width: 900px;
height: 500px;
background-color: #ccc;
}
.son{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="fa">
<div class="son"></div>
</div>
</body>
</html>
方式一:position+left+margin-left,适用于子盒子宽高已知的情况
<style>
.fa{
position: relative;
}
.son{
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;/*盒子宽度的一半*/
margin-top: -50px;/*盒子高度的一半*/
}
</style>
方式二:position+left+translate
<style>
.fa{
position: relative;
}
.son{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
方式三:子盒子定位+四个方向的距离为0+margin:auto
<style>
.fa{
position: relative;
}
.son{
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
}
</style>
方式四:弹性布局父盒子 {display:flex} 子盒子{margin:auto}
.fa{
display: flex;
}
.son{
margin: auto;
}
</style>
方式五:弹性布局 父盒子:display: flex; justify-content: center;align-items: center;
<style>
.fa{
display: flex;
justify-content: center;
align-items: center;
}
</style>