问题
在实际开发中遇到一个问题,子元素div.yellow
想通过margin-top
留白时,会把父元素div.green
也拉下来。
问题图片如下:
问题代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="margin: 0;">
<style>
.top {
height: 5px;
background: red;
}
.father {
width: 300px;
height: 300px;
background: green;
}
.son {
width: 150px;
height: 150px;
background: yellow;
margin-top: 50px;
}
</style>
<div class="top"></div>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
分析
可以从上面问题看到子元素son
加了margin-top
为50px
,此时父元素也跟随着下来了50px
,然而这并不是我想要的结果,那为什么会造成这个原因呢?
那我们来了解下盒模型规范:
In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.
所有毗邻的两个或更多盒元素的margin
将会合并为一个margin
共享之。毗邻的定义为:同级或者嵌套的盒元素,并且它们之间没有非空内容
、Padding
或Border
分隔。
再说了白点就是:父元素的第一个子元素的上边距margin-top
如果碰不到有效的border
或者padding
就会不断一层一层的找自己 “领导”(父元素,祖先元素)的麻烦。只要给领导设置个有效的border
或者padding
就可以有效的管制这个目无领导的margin
防止它越级,假传圣旨,把自己的margin
当领导的margin
执行。 对于垂直外边距合并的解决方案上面已经解释了,为父元素例子中的middle元素增加一个border-top或者padding-top即可解决这个问题。
解决方法
那如何解决这个问题呢,w3.org给出了思路:
- 一个浮动的盒与任何其它盒之间的margin不会合并(甚至一个浮动盒与它的流内子级之间也不会)
- 建立了新的块格式化上下文的元素(例如,浮动盒与’overflow’不为’visible’的元素)的margin不会与它们的流内子级合并
- 绝对定位的盒的margin不会合并(甚至与它们的流内子级也不会)
- 内联盒的margin不会合并(甚至与它们的流内子级也不会)
- 一个流内块级元素的bottom margin总会与它的下一个流内块级兄弟的top margin合并,除非兄弟有空隙
- 一个流内块级元素的top margin会与它的第一个流内块级子级的top margin合并,如果该元素没有top border,没有top padding并且该子级没有空隙
- 一个’height’为’auto’并且’min-height’为0的流内块级盒的bottom margin会与它的最后一个流内块级子级的bottom margin合并,如果该盒没有bottom padding并且没有bottom border并且子级的bottom margin不与有空隙的top margin合并
- 盒自身的margin也会合并,如果’min-height’属性为0,并且既没有top或者bottom border也没有top或者bottom padding,并且其’height’为0或者’auto’,并且不含行盒,并且其所有流内子级的margin(如果有的话)都合并了
简单的来讲,就是:
- 都用
float
来定位(有条件要求,适用范围较广) - 为父元素添加
overflow
不为visiable
的属性 (适用范围极广,推荐使用) - 为元素添加
border
(一般不用) - 使用绝对定位(适用范围较窄)
- 父元素增加
padding-top
属性(改变尺寸,不建议使用)