块盒常见的四种垂直居中方式
如果存在两个块级盒子,box1、box2,例如:
<!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">
<style>
.box1 {
width: 500px;
height: 500px;
background-color: black;
}
.box2 {
width: 100px;
height: 100px;
background-color: rgb(39, 109, 170);
}
</style>
<title>Document</title>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
已知宽高
.box1_position{
position: relative;
}
.center{
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
<div class="box1 box1_position">
<div class="box2 center"></div>
</div>
未知宽高(宽高不确定)
方式一:display: flex
.center{
display: flex;
justify-content: center;
align-items: center;
}
<div class="box1">
<div class="box2 center"></div>
</div>
方式二:定位 + transform
.box1_position{
position: relative;
}
.center{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="box1 box1_position">
<div class="box2 center"></div>
</div>
方式三:定位 + margin
.box1_position{
position: relative;
}
.center{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div class="box1 box1_position">
<div class="box2 center"></div>
</div>
注意:在使用absolute
定位时,该定位是相对于最近的有定位的父级进行定位的,如果没有找到有定位的父级,那么就相对于文档定位,因此在使用absolute
时需要给父级添加定义