方法1:利用定位的方法来实现
!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>
.parentBox{
width: 500px;
height: 500px;
border: 1px solid #000
position: relative; //父盒子设置相对引用
}
.child{
width: 100px;
height: 100px;
background: red;
position: absolute; //子盒子设置绝对引用
top: 50%; //向下移动百分50%
left: 50%; //向左移动百分之50%
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<!-- 方法1 :定位方法 -->
<div class="parentBox">
<div class="child"></div>
</div>
</body>
</html>
方法2: margin:auto的方法
* 方法2: margin:auto
.parentBox{
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.child{
width: 100px;
height: 100px;
background: red;
position: absolute;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
} */
<body>
<!-- 方法2: margin:auto的方法 -->
<div class="parentBox">
<div class="child"></div>
</div>
</body
第三种方法:利用 display:table-cell
.parentBox{
width: 500px;
height: 500px;
border: 1px solid #000;
display: table-cell;
vertical-align:middle;
text-align: center;
}
.child{
width: 100px;
height: 100px;
background: red;
display: inline-block;
<body>
<!-- 利用 display:table-cell -->
<div class="parentBox">
<div class="child"></div>
</div>
</body>
第四种发法:display:flex布局
.parentBox{
width: 500px;
height: 500px;
border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
}
.child{
width: 100px;
height: 100px;
background: red;
}
//第四种发法:display:flex布局
<div class=parentBOx>
<div class='child></div>
</div>
第五种:利用 transform
.parentBox{
width: 500px;
height: 500px;
border: 1px solid #000;
display: flex;
position: relative;
}
.child{
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50px,-50px);
}
<!-- 第五种:利用 transform -->
<div class="parentBox">
<div class="child"></div>
</div>
第六种:计算位置的方式
公式: 父盒子高度或者宽度的一半减去子盒子高度或者宽的的一半。
.parentBox{
width: 500px;
height: 500px;
border: 1px solid #000;
}
.child{
width: 100px;
height: 100px;
background: red;
/* 解决margin塌陷,触发BFC */
display: inline-block;
margin-left: 200px;
margin-top: 200px;
}
<!-- 第六种:计算位置的方式 -->
<div class="parentBox">
<div class="child"></div>
</div>