前言:使得box1盒子在box盒中垂直居中
<!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>
.box{
width: 200px;
height: 200px;
background-color: aqua;
}
.box1{
width: 50px;
height: 50px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">123</div>
</div>
</body>
</html>
方式1: 使用定位和margin
父级设置relative,子元素设置absolute、top:0,bottom:0,margin:auto;
.box{
position: relative;
width: 200px;
height: 200px;
background-color: aqua;
}
.box1{
position: relative;
top:0;
bottom: 0;
width: 50px;
height: 50px;
background-color: pink;
margin: auto;
}
方式2:使用定位和transform
父级设置relative,子元素设置absolute、top:50%,transform:translateY(-50%);[适用于元素已知宽度和高度]
.box{
position: relative;
width: 200px;
height: 200px;
background-color: aqua;
}
.box1{
position: relative;
top:50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
background-color: pink;
margin: auto;
}
方式3:flex弹性布局
父级设置display:flex,align-items:center;
.box{
display: flex;
align-items: center;
width: 200px;
height: 200px;
background-color: aqua;
}
.box1{
width: 50px;
height: 50px;
background-color: pink;
margin: auto;
}
方式4:table布局方式
父级设置display:table-cell,vertical-align:middle;
.box{
display: table-cell;
vertical-align: middle;
width: 200px;
height: 200px;
background-color: aqua;
}
.box1{
width: 50px;
height: 50px;
background-color: pink;
margin: auto;
}