首先我们要理解auto的意思是什么,auto是自动填充剩余空间。
块级元素,即便我们设置了宽度,他还是自己占一行,在css的规范中,元素他的左外边距+左边框宽度+左内边距+内容的宽度+右内边距+右边框+右外边距=包含块的宽度,如果我们给他的左右外边距设置为auto的时候,他会实现平分剩下的距离,从而达到一个水平居中的效果。
但是块级元素的高度并不会自动扩充,所以他的外部尺寸是不自动充满父元素的,也没有剩余的空间,因此margin上下设置auto不能实现垂直居中。
但是我们可以通过 定位+margin 来实现;
但如果父元素是body,此方法不可行。
<!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>
.box {
width: 500px;
height: 500px;
position: relative;
background-color: pink;
}
.box div {
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>