深入理解“margin:auto”
"margin:auto"填充规则
1.如果一侧定值,一侧auto,则auto为剩余空间大小
2.如果两侧均是auto,则平分剩余空间 。
"margin:auto"的计算规则
"margin:auto"的计算规则可以被总结为:计算元素对应方向上应该获得的剩余空间大小。
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.father {
width: 300px;
height: 100px;
background-color: red;
}
.child {
width: 200px;
height: 100px;
background-color: blueviolet;
margin-right: 80px;
margin-left: auto;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
此时根据计算规则,左边还剩20px,设置了margin-left:auto,左边就会有20px的边距。
根据同样的原理,我们把子元素的margin-right去掉,设置margin-left:auto。这时就实现了右对齐的效果。相比float:right可好多了,既没有脱离文档流,也增加了页面弹性。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.father {
width: 300px;
height: 100px;
background-color: red;
}
.child {
width: 200px;
height: 100px;
background-color: blueviolet;
margin-left: auto;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
触发"margin:auto"计算的条件
条件可被总结为:width或者height为auto时,元素具有对应反向的自动填充特性,才可触发margin:auto的计算机制。我们知道,文档流方向 是向水流一样水平铺满,垂直方向是没有填充剩余空间 的 特性。因此,即使我们给容器定宽,定高也不能垂直居中。如果我们要实现水平垂直居中,我们就需要“格式化高度和宽度”,把原本应该填充的空间空出来。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.father {
width: 300px;
height: 200px;
background-color: red;
position: relative;
}
.child {
width: 100px;
height: 100px;
background-color: blueviolet;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
可以看到子元素实现了垂直居中。但此时的子元素的中心点与父元素的中心点没有对齐在一起 。若想了解父元素子元素中心点对齐方式,戳这里即可了解,《css3,水平垂直居中》