CSS Containment and content-visibility
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
What CSS Containment Does
Normally, a change anywhere in the page can force the browser to recheck the layout, style and paint of a much larger portion of the document than the part that actually changed. The contain property tells the browser that a specific element's internals are isolated, so changes inside it cannot affect anything outside it - letting the browser skip a lot of unnecessary rechecking.
.widget {
contain: layout paint;
}| Value | What it isolates |
|---|---|
layout | The element's internal layout cannot affect outside layout, and vice versa |
paint | Nothing inside the element is allowed to visually render outside its bounds |
size | The element's size does not depend on its children's content |
content-visibility: A More Practical Everyday Tool
.article-section {
content-visibility: auto;
}content-visibility: auto tells the browser to skip rendering work entirely for an element that is far off-screen, essentially treating it as if it does not exist until it scrolls near the viewport - then rendering it just in time.
Why This Matters for Long Pages
A page with hundreds of sections - a long article, a large product catalog - can have most of its content sitting off-screen at any given moment. Without content-visibility, the browser still calculates layout and paint for all of it up front; with it, only what is actually near the viewport gets that work done immediately.
Avoiding Layout Shift with contain-intrinsic-size
.article-section {
content-visibility: auto;
contain-intrinsic-size: 0 500px; /* estimated height while unrendered */
}Without a size hint, an unrendered section collapses to zero height, which can cause the page's scrollbar and scroll position to jump around unexpectedly as sections come in and out of view. contain-intrinsic-size reserves an estimated placeholder size to prevent that jump.