tags:

views:

147

answers:

3

Having the HTML below

<!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"&gt;
<body>
    <div style="width:400px;height:200px;background-color:Gray;margin-bottom:10px;"></div>
    <div style="width:400px;height:200px;background-color:Green;margin-top:10px;"></div>
</body>
</html>

the space between those two DIVs is only 10 pixels.

Why? Explain please.

+5  A: 

That behavior is called collapsing margins. The margin values are not added but the higher value is used:

Vertical margins may collapse between certain boxes:

  • Two or more adjoining vertical margins of block boxes in the normal flow collapse. The resulting margin width is the maximum of the adjoining margin widths. […]
  • […]
Gumbo
Is there a way to prevent this ?I don't like this behavior.
pixel3cs
Why don’t you increase the values to 20px?
Gumbo
I won't increase the value to 20px because I will use margin in other contexts, I will have ASP .NET controls placed randomly at runtime on different spaces
pixel3cs
This is not 'strange' behavior. It *is* how it is supposed to work.
Traingamer
You might be able to prevent the behaviour by using "clear:both" on the elements. I haven't tried it though.
DisgruntledGoat
+1  A: 

Here is a good explanation of margin collapsing. Basically, it seems that all adjacent margins will collapse into each other, per the CSS specification and against all common sense.

tghw
+1  A: 

if you want to have the desired effect you can use "padding" instead, margins always collapse

Rony
padding isn't good for my purpose because I use the background-color CSS property
pixel3cs
I think border is the right solution for this, but again, this is strange
pixel3cs