<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>常见的margin误区</title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
.out {
width:200px;
height:200px;
background-color:orange;
}
.in {
width:100px;
height:100px;
background-color:pink;
}
</style>
</head>
<body>
<!-- 误区1:添加margin-top/margin-bottom可以撑开与父元素的距离 -->
<div class="out">
<div class="in" style="margin-top:20px;"></div>
</div>
<!-- 误区2:上下两个元素各自添加margin,那么撑开的距离是两个margin的总和 -->
<div class="out" style="margin-bottom: 100px;"></div>
<div class="in" style="margin-top: 100px;"></div>
<!-- 误区3:margin: 0 auto可以水平居中,那么margin: auto auto可以垂直水平都居中 -->
<div class="out" style="background-color: purple">
<div class="in" style="margin:auto auto;"></div>
</div>
</body>
</html>
上图:
可以看到如上图所示:
第一个粉色的方块并没有撑开和橙色方块的margin-top距离;
第二个图中粉色方块和橙色方块之间的距离为100px,而不是100+100=200px;
第三个图中粉色的方块虽然在紫色的方块内水平居中,但是并没有垂直居中。
第一个和第二个分别有一个特殊的别名:margin塌陷 / margin合并
至于第三个比较特殊,也没什么可以参考的,记住就行,垂直居中有其他的解决办法
-
margin塌陷的解决方式(选择以下其一即可)
- 给父元素添加 border: 1px solid transparent
- 给父元素添加 overflow: hidden
- 给父元素添加 display: inline-block / inline-table / inline-flex / inline-grid / table / flex / grid
- 给子元素添加 display: inline-block / inline-table / inline-flex / inline-grid
- 给父或子元素添加 position: absolute / fixed
- 给父或子元素添加 float: left / right
-
margin合并的解决方式
- 上下两个块元素如果要设置一定的margin来撑开的话,直接计算好距离,在其中一个添加margin-top / margin-bottom属性即可
-
垂直居中的解决方式
- 详细代码可以看我的另外一篇博文介绍,如果会利用position: absolute来设置相对于父元素的居中,请忽略