CSS Containment
The contain property allows you to indicate that an element and its contents are, as much as possible, independent of the rest of the document tree. This allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited area of the DOM and not the entire page, leading to significant performance benefits.
1. The Concept
When you change an element in the DOM (e.g., change its width), the browser often has to check the entire document to see if that change affects other elements. Containment tells the browser: "What happens inside this box stays inside this box."
2. Types of Containment
You can apply specific types of containment using keywords.
layout
Indicates that the internal layout of the element is totally isolated from the rest of the page.
- Nothing inside the element can affect the layout of anything outside.
- If the element is off-screen, the browser might skip laying out its children.
paint
Indicates that the descendants of the element don't display outside its bounds.
- If the element is off-screen (or obscured), the browser can skip painting its contents entirely.
- Acts like
overflow: hidden.
size
Indicates that the element's size can be computed without examining its descendants.
- The element behaves as if it were empty. You usually need to set an explicit width/height.
style
Indicates that properties that can have effects on more than just an element and its descendants don't escape the element.
- Mainly affects counters and quotes.
3. Combined Values
strict
Applies all forms of containment: layout paint size style.
- This provides the highest performance benefit but is the most restrictive (you must set the size manually).
.widget {
contain: strict;
width: 300px;
height: 200px;
}
content
Applies layout paint style.
- This is the most common use case. It allows the element to size itself based on its content, but isolates layout and painting.
.card {
contain: content;
}
4. Use Cases
- Third-party widgets: Ensuring ads or social buttons don't trigger page-wide reflows.
- Static Sites: If you have a long list of static items,
contain: contentensures that modifying one doesn't affect the others.
programming/css/css programming/css/content-visibility programming/javascript/vanilla/performance-api