Margin collapse and clearance [closed]

旧城冷巷雨未停 提交于 2019-12-22 01:29:26

问题


I am reading the W3C specs and I really don't understand that one :

If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.

Anyone could explain or JSFiddle it for me ?


回答1:


Yes. Take a look at this jsfiddle in either Firefox or IE.¹

<style>
  .case { width:200px; background-color:yellow; }

  .container { background-color:lightblue; margin-bottom:70px; padding-top:0.01px; }
  .preface { float:left; height: 58px; width: 100px; border: 1px solid red; }
  .one .intro { clear: left; margin-top:60px; }
  .two .intro { clear: left; margin-top:59px; }
</style>

<div class="case one">
    <div class="container">
        <div class="preface">
            lorem ipsum
        </div>
        <div class="intro"></div>
    </div>
    after
</div>
<hr>
<div class="case two">
    <div class="container">
        <div class="preface">
            lorem ipsum
        </div>
        <div class="intro"></div>
    </div>
    after
</div>

(The cases are identical apart from the class name "one" or "two" and their applied CSS. The padding-top:0.01px; is to stop the margin-top values of the intro block from collapsing into the margin-top of the container)

When an element has a clear value applied such that its box actually moves down, it said to have clearance. We can see that this happens in case two. In case one, the box is still has clear:left but its top margin is large enough that the element box does not need to move, so it does not have clearance.

Now look at the result.

In case one, the 70px bottom margin on the container collapses with the top-margin of the .intro div leaving a single 70px distance between the top of the .container div and the text "after". In case two, because the .intro div has clearance, in accordance with the quoted piece of the spec, the bottom margin of the container must not collapse with the top margin of the .intro div. So that top-margin is applied, resulting in the lightblue background area, and then the bottom-margin of the container is applied separately, resulting in the yellow background area.

¹Unfortunately, Chrome gets this horribly wrong.



来源:https://stackoverflow.com/questions/25350805/margin-collapse-and-clearance

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!