Clean Markup

Isolating DOM Subtrees with the CSS contain Property

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;
}

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

← Home