DEV Community

Cover image for Understanding CSS Layout Algorithms

Posted on

Understanding CSS Layout Algorithms

The mental model shift that makes CSS more intuitive

Up until that moment, I had been learning CSS by focusing on the properties and values we write.
I figured that if I understood broadly what each property did, I'd have a deep understanding of the language as a whole.

Image description

The key realization I had is that CSS is so much more than a collection of properties. It's a constellation of inter-connected layout algorithms. Each algorithm is a complex system with its own rules and secret mechanisms.

❔ Have you ever had the unsettling experience of writing a familiar chunk of CSS, something you've used many times before, only to get a different and unexpected result?
It's super frustrating. It makes the language feel inconsistent and flaky.
❔ How can the exact same CSS input produce a different output??

Image description

This happens because the properties are acting on a complex system, and there's some subtle context that changes how the properties behave. Our mental model is incomplete, and it leads to surprises!

Layout algorithms

So, what is a “layout algorithm”? You're probably already familiar with some of them. They include:

  • Flexbox
  • Positioned (eg. position: absolute)
  • Grid
  • Table
  • Flow

(Technically, they're called layout modes, not layout algorithms. But I find “layout algorithm” to be a more helpful label.)

❓ How can this be? We haven't set position: relative anywhere!
we have 3 siblings arranged using the Flexbox layout algorithm.

The middle sibling sets z-index, and it works. Try removing it, and notice that it falls behind its sibling.

This works because the Flexbox algorithm implements the z-index property. When the language authors were designing the Flexbox algorithm, they decided to wire up the z-index property to control stacking order, just like it does in Positioned layout.

This is the critical mental-model shift.

CSS properties on their own are meaningless. It's up to the layout algorithm to define what they do, how they're used in the calculations.

To be clear, there are some CSS properties that work the same in all layout algorithms. color: red will produce red text no matter what. But each layout algorithm can override the default behavior for any property. And many properties don't have any default behavior.

❓ Did you know that the width property is implemented differently depending on the layout algorithm?

If you liked this article, consider buying me a coffee - ☕.

Discussion (0)