Content Visibility
Content visibility is a CSS property that lets you control an element’s rendering. For example, You can use it to skip rendering off-screen elements dramatically improving performance.
Imagine you have a long page with many sections. You can give each section a content-visibility: auto
property. This will tell the browser to skip rendering the section until it’s visible in the viewport.
section {
content-visibility: auto;
}
If the section is not visible, the browser will skip rendering it, saving resources. When the section becomes visible, the browser will render and remember it for future use.
There’s one issue with this approach, though. If the section is not rendered, its height will be zero. This is not ideal because the scrollbar will jump whenever a new section becomes visible.
To fix this, you can use contain-intrinsic-size
to specify the element’s height when it’s not rendered:
section {
content-visibility: auto;
contain-intrinsic-size: auto 100px;
}
This tells the browser that each unrendered section should have a height of 100px. The auto
means that once the element becomes invisible again it will retain the rendered height instead of going back to be 100px.
Content visibility is part of the CSS Containment Spec and has many other use cases. Check out the links below to learn more.