tags:

views:

32

answers:

1

Here is my CSS (simplified):

body {
    background: url('bg.gif') left top;
}
#content {
     background: #ddd;
}
.box {
    overflow: hidden;
    margin-top: 10px;
    background: #1e1e1e url('left-bottom-corner.gif') left bottom no-repeat;
}

And the markup:

<div id="content">
    <div class="box">
        <p>lorem ipsum</p>
    </div>
</div>

Now the problem. In the place where the .box has 10px top margin, the background of #content div is not visible, instead, the background of the body is visible.

I cannot use padding because I need to style the .box divs to have round borders and their own background, so I have to use margin.

How can I fix this incorrect behaviour?

+3  A: 

It's not a bug - it's called margin collapsing.

You could do with preventing the margins from touching - this is why adding padding or a border fixes it.

Greg
I read that article and it seems to me it has nothing to do with my problem, there are no two margins touching anywhere. There is just one top margin, there is no toher margin above it. So there is nothing to collapse. The margin creates the correct space (10px). The problem is why the background of the body is visible and not the background of the #content div.
Richard Knop
Excellent! Finally an answer to one of the last remaining css-mysteries for me. And a great article to explain it too. Thanks, Greg. I knew about margin collapsing, but never would have guessed it could cause "too much" margin.
Magnar