Internet Explorer 8: Top margin missing from first element after floated elements and clearing <div>
We're not really sure what IE8 thinks it is doing here. What we can say for certain is that IE6, IE7, Firefox, and Safari all render our test markup as we would expect it to be rendered. IE8 is the only browser which gets the rendering wrong.
What we have is:
- Containing div to define the overall width
- One left floated div
- One right floated div
- Clearing div (clear: both)
- Following div with margin: 10px 0 0 0;
In IE, the top margin on the final div is missing. In all other browsers we have tested (including IE6 and IE7), it is displayed correctly.
Here's the code:
<div style="width: 400px;">
<div style="float: left; background: #CCCCFF; width: 150px; height: 100px; display: block;">
Left Floated <div>
<div style="float: right; background: #CCFFCC; width: 150px; height: 100px; display: block;">
Right Floated <div>
<div style="clear: both;"></div>
<div style="background: #00FFFF; margin: 10px 0 0 0; height: 200px; width: 400px">
<div> with margin: 10px 0 0 0;
In Firefox, IE6 and IE7, we'll see something like this:
In IE8, we'll see this:
Where's the top margin gone?
We don't know. What we do know, is that any of the following changes will make the margin re-appear:
- Remove the containing <div> altogether
- Add CSS float: left to the <div> with the missing margin
- Add a containing <div> around the two floated divs and the clearing div. This would be our preferred method
Good luck out there, folks. It looks like IE8 is going to be another headache for HTML developers.
Thanks should go to buti-oxa on the stackoverflow.com forums, who has pointed out that what IE8 is doing here is collapsing the margin into the containing <div>. This would explain why the top margin re-appears where expected when the containing div is removed.
Whilst there might be a question as to whether IE8 is in the right here, we would argue that this requires IE to ignore the 3 preceeding <div>s including the clearing <div>, and behave as if the final <div> were the first-child of the containing <div> - this doesn't seem like the right way to render this markup, but it seems pretty clear that this is what IE8 is doing.