CSS Containment
CSS containment declares that an element subtree is independent of the rest of the document, so the browser can skip reflowing or repainting outside the subtree when it changes.
Definition
CSS containment (the contain property) tells the browser that an element subtree is independent in one or more respects — layout, paint, style, size — so that a change inside the subtree does not invalidate the layout or paint of the rest of the document, limiting the rendering work to the subtree.
Context and scope
Applied in widget boundaries, list items, and any element whose internal changes should not trigger a full-document reflow.
Common misconceptions
- Containment is just optimization — it is optimization with a correctness contract; declaring containment the element does not satisfy produces wrong layout
- contain: strict is always safe — it is safe only if the element size does not depend on its contents; otherwise the element is sized wrong
Anti-patterns
- Declaring layout containment on an element whose size depends on its content, producing a zero-height element
- Applying paint containment without layout containment, so the element is painted independently but still reflows the document
Related concepts
Authoritative source
What it is
CSS containment (the contain property) tells the browser that an element subtree is independent in one or more respects — layout, paint, style, size — so that a change inside the subtree does not invalidate the layout or paint of the rest of the document, limiting the rendering work to the subtree. Applied in widget boundaries, list items, and any element whose internal changes should not trigger a full-document reflow. The browser is a hostile, shared, single-threaded (for JS) environment where every millisecond of main-thread work is a millisecond the user cannot interact.
How it works
The rendering pipeline — style, layout, paint, composite — is incremental and can be invalidated by any DOM change. Performance work targets avoiding the expensive phases (layout, paint) and scheduling the rest in idle callbacks or off the main thread. Loading work orders resources by their impact on the critical path: render-blocking scripts are deferred, images get fetch priority, and the server pushes what the client will need next.
When to apply and pitfalls
Apply when user interaction latency or load performance has a measured business impact. The pitfall is micro-optimizing a function while the page ships a megabyte of render-blocking JavaScript — the dominant cost is structural, not algorithmic. Another is measuring in the ideal lab profile and missing the long-tail devices and networks where most users actually live.