Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

CSS Containment Modules

DZone's Guide to

CSS Containment Modules

While they don't enjoy widespread browser support (yet), CSS's containment modules allow for optimizing your components' performance.

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

One of the new hidden gems in the new CSS modules, which is supposed to drop in new browser versions in the future, is CSS containment. In this short post, I’ll explain what is the new contain property and why you will want to use it.

CSS Containment Module

The CSS containment module defines a new indication, using the contain property, that an element’s subtree is independent of the rest of the page. This will enable browsers to optimize the performance of rendering/painting.

Let’s take an example of a third-party component that we use in our web page. When something changes in the component, it can make a chain reaction that will end in a whole web page reflow or repaint. Using the new containment module, we can indicate that the component is independent and therefore changes in that the component won’t affect the whole web page and vice versa.

Another interesting use case is the HTML5 custom elements API. CSS containment can be very helpful combined with custom elements when you want to indicate containment of the element you are creating.

The Contain Property

In order to force element containment, you will use the new contain property. Currently, the contain property can get the following values:

none | strict | content | [ size || layout || style || paint ]


The none value is the default value. Each value sets a different containment model. For example, using the layout value indicates that nothing outside the element can affect the layout of the element. You can take a look at a benchmark that shows the performance gain when using the property here.

Since we are talking about a CSS property it is very easy to use it:

.widget-name {
   contain: layout;
}


In the example, widget-name is a class that a third-party component is using and we set the contain property on it.

Summary

CSS containment isn’t supported by the major browsers except Chrome and Opera (at the time I’m writing this post). When it is widely adopted in browsers, it will enable us to optimize different web page components' performance.

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:
css ,module ,web dev ,containment ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}