views:

35

answers:

2

Safari 4 seems to be ignoreing my margins unless I add a border. The following example renders left and right margins but no top or bottom. If I add a border it renders as expected. Am I doing something wrong or am I going to have to add borders (albeit transparent ones) to every element with margins just for Safari?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>testing</title>
<style>
    body {background-color:#666;}
    div {display:block; position:relative; margin:0; padding:0;}
    .background {background-color:#990000;}
    .foreground {background-color:#fff; margin:10px; padding:10px;}
</style>
</head>
<body>
    <div class='background'>
        <div class='foreground'>
        foreground
        </div>
    </div>
</body>
</html>
+2  A: 

It's a normal weird behaviour calling margin (edited, sorry i'm french) collapse. To simply avoid it add overflow:auto; on the container.

.background {background-color:#990000; overflow:auto;}
MatTheCat
Yes, your margins are *collapsing*, which is normal. [This article](http://www.complexspiral.com/publications/uncollapsing-margins/) might help explain things.
Matt Gibson
Thanks. Interesting article - It might be correct but that doesn't make it right! All other browsers seem to understand what is meant by a margin and cope with combining them in the case of adjacent margined elements.
Moob
@Moob Does this really work as you expect in all other browsers? I wouldn't expect it to... Firefox seems to collapse the top/bottom margins with your example code for me (http://jsfiddle.net/8tbjW/). Normally it's just IE that's broken, though I do take your point that the non-collapsing behaviour can seem more sensible sometimes.
Matt Gibson
Yeah, you're right... It's the same in FF. Its astounding that I have not run into this issue before! Thanks.
Moob
+1  A: 

It is called margin collapse. When a top and bottom margin are touching each other, the margins will combine into the greater of the two.

The reason it works "correctly" when you add the border is because you created a 1px separator for the margins so they no longer collapse. Interestingly, if you instead added a empty div with no height/borders, the margins would still collapse because the div takes up 0px space.

Moses
Okay, but in this example the combined margin is 0 + 10px = 10px. Thanks for the info though.
Moob