Display flow-root
Extra
Many years ago, flow-root
has been added as another value for the display property. I’ve encountered it in DevTools, where it is shown among the other values in the display property dropdown, but I never felt the urge to learn more about it. Until now.
Part of CSS Display Module Level 3, the idea behind flow-root was to end the clearfix hack, which has been a thing back in the day, and something you’ve been actively using if you have been in web development since way back.
Back to the question, has flow-root been the end of the clearfix hack? Yes. However, the layout methods flexbox and grid have been the true end of the clearfix hack.
Hack aside, there is at least one other thing you can use flow-root for, but it all works in tandem with floated elements.
№1: Hack obsolescence
The raison d'être for display: flow-root
, if you apply it to an element that contains a floated element, that floated element will be contained.
№2: Non-interference
You can also add flow-root to an element near a floated element, so the floated element doesn’t end up atop the other element. Such interference does not happen for the actual text, but if said element has a background color or border, it will be covered by the floated element.
Without flow-root, the text goes below the image, not wasting space. With flow-root, borders and backgrounds make more sense. But you cannot have it both ways, the box that contains the text will always be a rectangle, and not a weirdly shaped Tetris piece.
Closing remarks
According to MDN’s display page, this is what happens when you set flow-root:
The element generates a block box that establishes a new block formatting context, defining where the formatting root lies.
Okay‽
MDN’s block formatting content page is worth a read too.
Wait! What if—instead of going down that MDN rabbit hole—we just apply flow-root everywhere? After all, this seems to be the better behavior, no matter if a page has floating elements or not.
Well, no. It’s not a drop-in replacement for the block (i.e. block flow
) display value. For starters, margins no longer collapse when you use flow-root, and there’s probably more. Here be dragons.
I rarely use floats these days, so the float relationship may explain why I’ve never felt the need for the flow-root display value. After you’ve played with my interactive example on CodePen, you’ll probably file this under ‘good to know’ and move on. Or you’ve stopped reading several paragraphs ago, because you are already playing Tetris.