Heim  >  Artikel  >  Web-Frontend  >  css子元素的margin-top为何会影响父元素_html/css_WEB-ITnose

css子元素的margin-top为何会影响父元素_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:45:391268Durchsuche

 

详细内容请点击

 

这个问题困惑了很久,虽然没有大碍早就摸出来怎么搞定它,但始终不明白原因出在哪里,如果只是IE有问题我也不会太在意,可问题是所有上等浏览器都表现如此,这样叫我怎能安心?今天总算下狠心查出来怎么回事,居然是CSS2.1盒模型规范……虽然很别扭,非常别扭的规定。   问题如下图,两层Div结构,Outer Div属性为“margin:0 auto”,本该紧贴外框顶部的,如果没有Inner Div,或者没有Inner Div的“margin-top”属性,一切如预期。但是当Inner Div设置了“margin-top:10px”之后,它的父元素Outer Div也被撑出来一个本不该有的“margin-top:10px”效果。

Inner Div [margin-top: 10px]

Outer Div [margin: 0 auto]

HTML Demo Area

这个“问题”……它是CSS2.1的盒模型中规定的内容??Collapsing margins:

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分隔。

这就是原因了。“嵌套”的盒元素也算“毗邻”,也会 Collapsing Margins。这个合并Margin其实很常见,就是文章段落元素

,并列很多个的时候,每一个都有上下1em的margin,但相邻的

之间只会显示1em的间隔而不是相加的2em。这个很好理解,我就是奇怪为什么W3C要让嵌套的元素也共享Margin,想不出来在什么情况下需要这样的表现。   这个问题的避免方法很多,只要破坏它出现的条件就行。给 Outer Div 加上 padding/border,或者给 Outer Div / Inner Div 设置为 float/position:absolute(CSS2.1规定浮动元素和绝对定位元素不参与Margin折叠)。   更多信息,关于不同值的margin折叠后表现的计算方法等等,可自行查阅W3C的CSS2.1规范:Collapsing margins。

解决办法比较多:

1、给父级加overflow:hidden或padding、border;

2、使用padding代替margin

来源:http://www.cnblogs.com/hejia/archive/2013/05/26/3099697.html

 

更多html5内容请点击

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn