CSS Containment and content-visibility

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;
}
ValueWhat it isolates
layoutThe element's internal layout cannot affect outside layout, and vice versa
paintNothing inside the element is allowed to visually render outside its bounds
sizeThe 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.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.