margin-top not working with clear: both

Vishal picture Vishal · Nov 16, 2010 · Viewed 34.6k times · Source

Why is the margin:top for 'Main Data' not working in the code above?

Answer

Pointy picture Pointy · Nov 16, 2010

You could put the two floated divs into another one that's got "overflow: hidden" set:

<div style='overflow:hidden'>
  <div style="float: left;">Left</div>
  <div style="float: right;">Right</div>
</div>
<div style="clear: both; margin-top: 200px;">Main Data</div>

edit — To add a bit to this 5-year-old answer: I think the cause of the confusing behavior is the somewhat complicated process of margin collapse. A good trick with the original HTML from the OP is to add a CSS rule like this:

div { border: 1px solid transparent; }

Poof! Now (without my additional <div>) it works fine! Well, except for that extra pixel from the borders. In particular, I think it's a combination of the way that clear: both works and the margin collapse rules that result in the unexpected layout from the code in the OP.

edit again — For the complete (and, I think, completely accurate) story, see Mark Amery's excellent answer. The details have some complexity that this answer glosses over.