码迷,mamicode.com
首页 > 其他好文 > 详细

margin collpase(margin合并)小结

时间:2015-09-03 16:33:24      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

一、前言

标题的margin collpase(margin 合并),江湖又成“margin 塌陷”;以前对margin 合并的理解就是在紧邻的兄弟元素中上一个的margin-bottom会和下一个的margin-top合并;紧邻父子元素,margin-top会合并;然后,就没有然后了。直到实际项目中,看到已有项目中存在父子margin没有合并的现象,但是自己又理解不了的时候,才人认真的将w3c中有关margin合并的规则看一遍。

二、margin collpase

margin collpase 规则

  1. root Element 不合并
  2. 相邻(adjoining )margin合并为最大值

第一条中的root Element,即BFC,不知道BFC为何物的,待会儿请看下边的相关链接,不过这个不影响下边内容的理解

第二条中的相邻(adjoing)的条件:(必须三条都满足)

  1. 在同一个BFC中,且在文档流中的块级元素
  2. 相邻的margin之间没有行内元素(line boxes)、内边距(padding)、边框(border),如果是高度为0的行内元素无效如(空标签<span><span>等)
  3. margin都是垂直方向

相邻规则:

  1. top margin of a box and top margin of its first in-flow child(元素的margin-top以及它在文档流中的第一个子元素的margin-top)
  2. bottom margin of box and top margin of its next in-flow following sibling(元素margin-bottom和它在文档流中后边紧邻兄弟元素的margin-top)
  3. bottom margin of a last in-flow child and bottom margin of its parent if the parent has ‘auto‘ computed height(文档流中最后一个子元素的margin-bottom和它父元素的margin-bottom,前提是,父元素的height是auto的)
  4. top and bottom margins of a box that does not establish a new block formatting context and that has zero computed ‘min-height‘, zero or ‘auto‘ computed ‘height‘, and no in-flow children(非BFC元素的margin-top和margin-bottom,并且这个元素的min-height为0,height为0或者auto,且没有文档流内的子元素)

margin负值合并规则:

When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins‘ widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.(多个margin合并的时候,合并得到的是最大值。如果margin是负值,正值最大的margin减去负值绝对值最大margin的绝对值就是最终margin;如果没有正值margin,结果就是0减去负值绝对值最大margin绝对值)

三、阻止margin collpase

上边的margin collpase规则是2条,针对这两条有两种行之有效的方法:

  1. 将元素转变为BFC,具体查看BFC相关内容中的产生规则(当时在项目中看到的overflow:hidden就是符合这条原理)
  2. 将相邻的margin切断,从相邻条件的三条中,我们可以看到,第2条还是可以阻止的。给元素添加padding,border。如果设计中没有border,可以将border设置为透明(border-color:transparent;)

Technorati 标记:

margin collpase(margin合并)小结

标签:

原文地址:http://www.cnblogs.com/bjchenxn/p/4780306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!