Understanding the CSS box model and floats

I went with the standard two-column layout for this site: content and sidebar. I wanted the columns to have “fluid width”, equal height, and different background colors, so I referenced this article and used the " Nicholas Gallagher method" to implement it.

I recommend checking out the Gallagher method example at CSS-tricks with the browser’s element inspector to see what’s going on there, as it demonstrates the use of CSS pseudo-elements, the overflow: hiddentrick” (to create a Block Formatting Context), and how floats and absolutely/relatively-positioned elements are laid out.

Here are some examples that I came up with to try and come to grips with how floats are laid out:

Given this CSS:

And this HTML:

We get:
First div
Second div
This is a third div with some content in here that might wrap around. Still more content. Again more content.

The first and second divs (.fst and .snd) are floating, and placed next to each other on the same line. The third div (.thd) is not floating, and participates in layout as though the other divs weren’t there: the outer top and left edges of the third div’s margin box are touching the top-left corner of the content box of the containing element (the .example div). Note that the border of .thd is visible in the upper-left corner of the container because .fst is offset.

Because the first/second divs are floating, and because the first words of .thd’s content are able to fit alongside them, the first line-box of .thd begins horizontally adjacent to those two, and the content continues below them. According to the CSS box model spec, the third div’s content must lie outside the margins of the first/second div.

In contrast, if the third div’s content area is too narrow to accommodate width of the adjacent floats, then the first line-box of .thd will be shifted down below them.

First div
Second div

This is a third div with some content in here that might wrap around. Still more content. Again more content.

The relevant quote from the spec is:

[L]ine boxes created next to the float are shortened to make room for the margin box of the float. If a shortened line box is too small to contain any further content, then it is shifted downward until either it fits or there are no more floats present.
CSS basic box model specification

Check out this fiddle if you would like to play around with the examples.

Comments