Search code examples
cssmarginw3c

Margin collapse and clearance


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 ?


Solution

  • Yes. Take a look at the below snippet [JSfiddle] in either Firefox or IE.¹

    .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; }
    <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.

    JSFiddle screenshot

    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.