方式一:用定位结合自身高度宽度的方式实现盒子水平垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.wrapper {
position: relative;
width: 200px;
height: 200px;
background-color: skyblue;
}
.box {
position: absolute;
left: 50%;
margin-left: -50px;/* 负的自身宽度的一半 */
top: 50%;
margin-top: -50px;/* 负的自身高度的一半 */
height: 100px;
width: 100px;
background-color:pink;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>
方式二:纯定位实现盒子水平垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.wrapper {
position: relative;
width: 200px;
height: 200px;
background-color: skyblue;
}
.box {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
height: 100px;
width: 100px;
background-color:pink;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box"></div>
</div>
</body>
</html>
注:设置为绝对定位的标签框脱离文档流,并相对于其包含块定位,包含块可能是文档中的另一个标签(开启了定位的父元素)或者是初始包含块(html,当没有开启了定位的父元素时)