DEV Community


My best CSS 2019 performance tip: contain

rrees profile image Robert Rees ・2 min read

The best CSS performance tip I had in 2019 was to use the contain property.

contain creates an new isolated context for the DOM element that is attached to. For most web pages the main sections of the page tend not to depend on one another's states. A footer or sidebar for a page, for example.

Where the real power comes from though are pages that have many repeating blocks. Things like search results, product cards and even table rows can all be isolated while having local state and behaviour.

Even for older code there are advantages in terms of resetting stacking and block contexts to something that is more intuitive. Even the clipping rules are probably more more what you'd expect for a block on-screen that the default page-based rules.

The final magical thing about contain is that you don't have to get it right. If the browser detects that it needs to repaint that section of the DOM, you pay the performance penalty and it does. The emphasis is therefore on you to make sure you don't implement changes that invalid its use. On the other hand nothing goes wrong in situations where you unexpectedly find a dependent change or there are circumstances in which the UI is not as isolated as your mental model predicted.

For a reasonable well-implemented site the performance benefit it probably going to be subtle and take some time in the dev tools to notice but it is a simple non-breaking change that allows you embed a bit of your mental model into your HTML and maybe avoid you having to use a "clearfix" class ever again.

Discussion (0)

Editor guide