Recently, while experimenting with CSS and floating elements, I encountered an unexpected behavior that caught me off guard. I found myself questioning why this had never come up before.
If you have a div (let's call him Bob) and try to float him next to another div (let's name him Jimmy), it only works if
- Jimmy is also floated
- Jimmy comes after Bob
For example:
<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;
}
the layout looks normal, but if we switch #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 see a different outcome.
The reason behind this behavior likely relates to the box model and how floats are defined, but what exactly?
Feel free to experiment with it here