Go back

CSS Containment: an underrated performance boost ๐Ÿš€

How contain isolates the DOM to reduce layout, paint and style recalculations, and the limitations to watch for.

CSS Containment: an underrated performance boost ๐Ÿš€

I came across an excellent CSS Wizardry article about contain, and it seems many people still underestimate it.

contain lets you isolate part of the DOM and tell the browser: โ€œEverything that happens inside does not affect the rest of the page.โ€
As a result, the browser can significantly optimize layout, paint and style recalculations.

The author covers the main values:

  • contain: layout: layout isolation
  • contain: paint: nothing extends beyond the boundaries
  • contain: size: the element does not affect its parentโ€™s dimensions
  • contain: content: everything together at once, the most common use case

Especially useful for:

  • widgets
  • complex components
  • virtualized lists
  • any isolated UI blocks

๐Ÿ’ก Essentially, this is a way to manually tell the browser where an elementโ€™s influence ends, so it does not recalculate more than necessary.

But there are caveats:

  • you can accidentally break the layout
  • size does not always behave intuitively
  • not everything can be safely isolated

The article has plenty of examples and explanations of where this actually pays off.

Read

Copied