tags:

views:

358

answers:

2

According to the CSS 2.1 standard, the vertical margins of floating elements should not collapse with any adjacent elements.

See: http://www.w3.org/TR/CSS21/box.html#collapsing-margins

But actually this is not what happens in all browsers (FF, Safari, Opera and Chrome) except IE6 (didn't try with IE7 or IE8 though). Here's the code:

<!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" >
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1" />
</head>
<body>
<div style="margin-bottom:10px;">HEADER</div>
<div style="float:left;width:100%;margin:10px 0px;">Floating div</div>
<div style="margin-top:10px;">FOOTER</div>
</body>
</html>

Adding clear:both; to the footer div didn't make any difference.

I'm no expert in CSS so please correct me if my understanding is wrong

Edit:
Obviously my question caused some confusion. The code above is just for demonstrating the behavior I'm referring to, it's not a real problem that I'm trying to find a solution to.

A: 

I got it to resolve (IE7, FF) by adding:

<div style="clear:both;"></div>

BETWEEN the Floating div and the Footer.

[Edit:] When you float an element, and put an element after it that you want to start at the beginning of the next space, you should/must use a clearing element. Zack's right, too: If you're just stacking divs, you don't/shouldn't float anything.

John Dunagan
+6  A: 

In neither IE6 nor the standards browsers are the float's margins collapsing with its siblings. This is correct as per the quoted standard.

The difference in renderings is caused by IE6's interpretation of which margins flow together. (If you give each div a background colour it makes it easier to see what is happening here.)

Two or more adjoining vertical margins of block boxes in the normal flow collapse

With the normal flow defined thus:

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn't exist.

That is, they flow together and have adjoining vertical margins which may collapse. IE6 (and IE7 in Quirks Mode) gets this wrong, and thinks that the float breaks up the flow, causing no collapsing to occur.

With the general confusion surrounding vertical margins and collapsing, compounded by the still-extant browser bugs, I'd recommend avoiding vertical margins and using padding instead wherever possible.

bobince
Thanks for your explanation, actually I suspected the same thing but wasn't sure. As to using padding instead of margins, actually this is what I do for the same reasons you mentioned.
Waleed Eissa