Daily Shaarli

All links of one day in a single page.

February 15, 2024

Understanding Layout Algorithms

In this article Josh Comeau went in depth on why it matters to think of CSS as the parameter to the layout algorithms. This means for any layout problem, you must think of which layout algorithm you're using before deciding.

For example, z-index is not functioning by default. To use it you must set position: relative | relative. This is because the flow algorithm (think about Word) doesn't know about z-index. It only makes sense in the "Positioned" layout algorithm. And the position attribute is used to switch the positioned algorithm. Instead of saying z-index depends on the position attribute, it's better understood that it depends on the layout algorithm.

Another evidence is that properties are interpreted differently in different layouts. For example, width is hard-restriction for flow layout, but more fluid in a flexbox layout.

It's possible to declare conflicting layouts on the same element. But then there is a priority in which algorithm takes precedence. Two algorithms are never used simultaneously on the same element.

Identifying the algorithm:

  • flow (the default)
    • the core of flow layout are inline blocks and blocks.
  • positioned (when position is set), four variants: relative, absolute, fixed, sticky
  • float (when float is set)
  • table
  • flexbox (parent is display: flex)
  • grid (parent is display: grid)

There are quirks which are result of different layout algorithms. For example, when putting an img inside a box, it gets a little whitespace below it that are not padding/margin/border of either parent box or the image. This is because inline elements are aligned by baseline. And the flow algorithm adds a bit of vertical space below the baseline of inline element to ensure the bottom part of "g", "j", etc are visible. img by default is inline-block and its baseline is at its bottom edge (0). Now the problem is understood one can solve it in different ways.

How To Center a Div

Josh Comeau writes one of the best interactive css tutorial out there! I learned so much in this article. A few notes:

  • margin: auto makes the child take as much margin as possible.
  • width: fit-content uses all available space, but within the intrinsic size
  • margin-inline: auto is a shorthand for margin-left: auto; margin-right auto;
  • place-content: center is a shorthand for align-content: center; justify-content: center
  • difference between place-content and place-items in grid layout - the latter aligns items relative to the cell
  • the insight that css attributes are merely inputs to the underlying layout algorithm