Why does a floated div sometimes inherit the border of the next element?

Instead of trying to explain it, I'll give you the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
    <title>weird</title>
    <style type="text/css">
        div#sidebar {
            background-color: yellow;
            float: left;
            width: 200px;
        }
    </style>
</head>

<body>
    <!-- insert something here to shift the top 
         of the sidebar by the top margin of the following div
    -->
    <div id="sidebar">
        background-color: yellow;<br />
        float: left; <br />            
        width: 200px;<br />
    </div>

    <div style="margin-top: 200px;">div - margin-top: 200px;</div>
</body>
</html>

      

I am testing this in FF and Chrome. Funnily enough, IE6 behaves the way I thought was right. (?) I've reduced this down to the smallest replay I can. Basically, if you put text next to the comment, the sidebar will move to the top of the document as I expect. Otherwise, the sidebar seems to inherit the top edge of the next div.

What's happening?

+2


source to share


2 answers


This behavior, in my opinion, is correct. Floating block elements are drawn on one top edge. They must be at the same level. A workaround would be to work with an addon here.



+2


source


Not sure why the browser would look like this. I gave it a couple of tries and found that Opera and FF were doing it wrong. Although IE7 renders it correctly.

My CSS knowledge says the div should float to the left and the second div should be 200px below the top, mostly ignoring that the first div even exists.

By adding clear: on the left to the second div giving you



<div style="margin-top: 200px; clear:both;">div with big top margin</div>

      

It displayed correctly in Opera and FF, but now it is wrong in IE7. IE7 adds extra space. It displays 200px below the margin, not the top.

0


source







All Articles