<!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>练习</title>
<style>
* {
padding: 0;
margin: 0;
}
#wrap {
position: relative;
width: 300px;
height: 400px;
border: 1px solid teal;
margin: 0 auto;
}
/* 重要,实现盒子水平垂直居中 */
.inner {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div id="wrap">
<div class="inner"></div>
</div>
</body>
</html>
原因:margin:auto。其中auto存在平分剩余的空间意思。
上部分代码在浏览器中运行可以发现,子盒子在父盒子中水平和垂直方向上的外边距是平分。
需要注意的是,当left,top,right,bottom,四个属性同时设置值时,left和top的优先级高于其他两个,所以当我们将四个值同时设置为100px并且把margin:auto去掉时,那盒子就将以top和left来进行定位,此时可见剩余空间没有被平分。