
Isolating DOM Subtrees with the CSS contain Property
In large DOM trees containing thousands of elements, updating the text content, class list, or dimensions of a single component can trigger global style recalcs and layout passes that ripple up to the document root.
The CSS contain property provides a way to explicitly isolate an element's subtree from the rest of the document, signaling to the browser engine that internal changes will never affect external geometry.
Example
<div class="chat-widget">
<div class="message-stream">
<!-- Thousands of incoming chat messages -->
</div>
</div>
Implementation
.chat-widget {
width: 360px;
height: 480px;
contain: layout paint;
}
contain: layout: Guarantees that internal layout changes inside.chat-widgetnever trigger layout recalculations outside the box.contain: paint: Guarantees that descendants will never display outside the element's bounding box, allowing offscreen widgets to be skipped during painting.contain: strict: Combineslayout,paint,size, andstylecontainment for maximum rendering optimization.
Main Point: The contain property stops layout and paint recalculations from rippling across the page, keeping large single-page applications at 60fps.
Credits
Photo by Joel Filipe on Unsplash