CSS Floats

CSS floats can yield unique and visually pleasant layouts, though for most cases CSS3 now has simpler and easier layout algorithms. This morning I want to describe how WebKit implements CSS floats.

It’s still fairly simple, though the data dependencies aren’t necessarily. Which makes it a bit harder for a browser engine like Servo aiming for massive parallelism.

The first step is to remove floats from the flow during layout (in order to figure out their y position) into their own lists held by the containing block. These’ll be flagged for which side they’re on and buffered up for layout.

This list will be prepopulated upon laying out the block with any “intruding” floats from the previous sibling, converted to the local coordinate system. From there it just laysout unpositioned floats, track where to put on the y axis, and their bottommost position.

The unique thing about inlines however is that inline text wraps around it, and this is implemented by factoring existing floats into the calculation of each line’s width. And by converting any new floats on that line into empty boxes at the end of that line.

As for how the floats are stored in memory, it’s in a shallow wrapper around a Red-Black Tree (a balanced binary tree) sorted by their y-interval.