unexpected margin with very simple html

后端 未结 5 528
说谎
说谎 2021-01-19 00:29

I have a very simple html. The red div is inside the blue div and has a 10 px top margin. On non-ie browsers, the blue box is 10 px apart from the top of viewport and the re

5条回答
  •  无人及你
    2021-01-19 00:51

    As much as strager's answer already explains about as much as you need to know as to why it happens – namely that it happens the way it does in browsers other than IE because the specs say so – I think he picked the wrong quote from the section of the CSS 2.1 specification about collapsing margins.

    The point he quoted explains how margins can collapse, not how they can "move" to a parent element.

    This is rather what explains it:

    • If the top and bottom margins of a box are adjoining, then it is possible for margins to collapse through it. In this case, the position of the element depends on its relationship with the other elements whose margins are being collapsed.
      • If the element's margins are collapsed with its parent's top margin, the top border edge of the box is defined to be the same as the parent's.

    Or, in slightly more human-readable form in the Mozilla developer documentation:

    Parent and first/last child:

    If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

    As for how to fix it, I'd probably go for the overflow: auto solution Chris Lloyd suggested (as much as that may have side-effects).

    But then that really depends on what exactly the rest of your code looks like. In this simple example you could easily just change the margin on the child element to a padding on the parent element.

    Or you could float the child element, or absolutely position it...

    Or how about an inverse clearfix if you want to get really fancy:

    .outer:before {
        content: ".";
        display: block;
        height: 0;
        clear: both;
        visibility: hidden;
    }
    

提交回复
热议问题