views:

139

answers:

1

Hello all,

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"&gt;
<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>
A: 

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.

BalusC
Thanks, firstly I have mis-applied the has-layout fixes when trying to fix this by trying to _give_ my elements layout. In any case it's easier to give layout than to remove it! Regarding your solution: I won't be able to use the padding option. Although I didn't specify it in my original question, I need the `<p>` elements to have a background colour, and to be seperated from the `<hr>` elements with a margin.
Nicolas
Ugly, but works: use `<br>` accordingly. The background gives the element layout and since you need it...
BalusC
ok, the hasLayout explanation was the key. I didn't try to attack that issue directly, but accepted that I couldn't expect the margins to collapse in this instance. All that I did was remove all margins from the relevant `<hr>` elements and only apply the margins to the `<p>` elements. It's not perfect there is still a little bit of expansion when viewed in IE7 compared to FF3/IE8 but not enough anymore to break the layout. Thanks
Nicolas