So I was fiddling around with CSS and floating the other day and stumbled upon an odd behavior (frankly I’m surprised I hadn’t encountered it before). I was puzzled as to the reason for it (as well as to why I didn’t already know…).
If you have a div (let’s call him Bob) and you try to float him next to another div (Jimmy), it only works if
- Jimmy is floated too
- Jimmy comes after Bob
So if we have:
<div class="container">
<div id="one">Main Content 1</div>
<div id="two">Sidebar 1</div>
</div>
with
.container {
overflow:hidden; /* this essentially clears the floats. You could remove it and add a clearfloat div instead */
margin-bottom:10px;
}
#one {
background-color:red;
margin-right:50px;
}
#two {
width:50px;
float:right;
background-color:blue;
}
we get;

but if we just swap #one and #two, keeping the same CSS:
<div class="container">
<div id="two">Sidebar 2</div>
<div id="one">Main Content 2</div>
</div>
we get:

Why? I’m sure it’s something simple (which makes me feel stupid) related to the box model and the definition of float, but what?
You can fiddle with it here
This is expected behavior.
First remember that floated elements are not part of the normal flow. The rest is in the following spec:
Basically your second example pulls
div#twoout of the document flow and shifts it to the right until it touches the outer edge of its sibling,div#one. Since it hasmargin: 50px;, there’s enough room fordiv#twoto fit.Your first example,
div#onehas already cleared that line as a block level element and thereforediv#twois floated right and aligned with the top of the current line.Read more from the W3C CSS2.1 Specification on Floats