Search code examples
cssinternet-explorer-7internet-explorer-6margin

Why won't the vertical margins between <p> and <hr> collapse in IE7


Perhaps I am missing something, but I can't explain this from any IE bug I know of. Why in this example do the margins of the <p> and <hr> elements collapse as expected in standards compliant browsers (i.e. FF3, IE8, etc) but not in IE7 (including IE8 compatibility mode)?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
    <title>IE7 Box Model</title>

    <style type="text/css">

        p {
            border: 1px solid #00f;
            background-color: #fefecb;
            margin: 20x 0 20px 0;
            }

        hr {
            margin: 20px 0 20px 0;
            }

    </style>

</head>
<body>
    <p>
        box 1
    </p>
    <hr />
    <p>
        box 2
    </p>
    <hr />
    <p>
        box 3
    </p>

</body>
</html>

Solution

  • This is related to the hasLayout bug. Here's an extract of relevance:

    Margin collapsing

    The hasLayout MS-property affects the collapsing of margins between a box and its descendants. According to the spec the top margin of a box with no top padding and no top border should collapse with the top margin of its first in-flow block-level child:

    In IE/Win this never happens when the box has layout: it seems that layout prevents the margins of the children to stick out of the containing box. Moreover when hasLayout is true, either on the container or on the child, other wrong margins computations show up:

    The best solution is simple but maybe drastic on existing designs: set margins on block elements to 0 and use padding instead so that it's consistent across the browsers. Paddings won't collapse.