日期:2014-05-17  浏览次数:20673 次

css之margin collapse(外边距叠加)

首先抛出问题:

  • “和父元素相同大小的子元素,设置了四边的Margin的子元素却向右侧平移了”(源自者也:http://zheye.org/asks/4e8582effd503c260d0004d7 )

  • stackoverfow:
  1. Margin on child element moves parent element

  2. Child elements with margins within DIVs

其实: 以上问题都源于css中的margin collapse,即外边距叠加。 以下内容源于css mastery second edition。

margin collapse发生的条件有,处于normal flow(正常文档流,而非postion: float || absolute),block元素间的垂直margin(margin-top, margin-bottom)。所以可以改变元素的定位(增加float属性或position: absolute)来取消margin collapse.

?

下面是margin collapse的几种情况:

1. 上下两div(上定义有margin-bottom, 下有margin-top): 叠加取较大的margin值



?2. margin collapse发生在父元素和子元素之间,前提是垂直边距间不存在padding(内边距)和边框。所以可以通过增加padding属性,或边框,防止叠加。如例子者也。



?3. margin collapse会发生在定义有垂直外边距的空元素,如下图



? 叠加也是连续的:




以上是margin collapse发生的几种情况。

其实 margin collapse 的存在有他自身的意义:


?补充:margin边界叠加问题以及ie和Firefox的不同解释

?

?

?