Reducing initial render work with content-visibility

With Interaction to Next Paint (INP) now part of the Core Web Vitals, rendering performance has moved to the forefront. A key factor in a fast page is minimizing the amount of work the browser must do right at load time. Long initial rendering tasks can delay user interactions, making the page feel sluggish. The CSS content-visibility property offers a way to defer that rendering, and it is now Baseline Newly available as of September 2024.

Jeremy Wagner

content-visibility is a CSS property that instructs the user agent to skip rendering work for elements that are still off-screen. On pages with a high number of DOM elements, this is a significant win: the initial page load triggers far less layout and paint work. The browser performs this work later, just in time for the element to enter the viewport.

demo with figures representing network results
In our article demo, applying content-visibility: auto to chunked content areas gives a 7x rendering performance boost on initial load. Read on to learn more.

How it works

To use the performance optimization, simply apply content-visibility: auto to off-screen elements.

.render-me-later {
  content-visibility: auto;
}

This rule relies on behaviors defined in CSS containment via the contain property. Containment is a technique for isolating parts of the DOM tree so that layout invalidation and recalculation can be scoped to those specific subtrees, preventing cascading rendering updates across the whole page. Without content-visibility, effectively using containment requires a deep knowledge of the different contain values and how to apply them.

When you set content-visibility: auto, elements automatically gain these containment properties. As a result, the browser initially treats the element as having a height of 0px, essentially not rendering it.

A note on scrollbars and sizing

This default zero-height behavior can lead to a notable side-effect: the page's scrollbar might shift as a user scrolls to content that hasn't been rendered yet. In many cases, fixing this requires adding the contain-intrinsic-size property, which lets you specify a natural size for elements that haven't yet be rendered.

Progressive enhancement and advantages

Even though content-visibility is a newer feature, a lack of support in any user's browser doesn't break the page. Since it's a CSS property, browsers that don't understand it will simply ignore it, allowing your layout to render as usual. The rule provides an additive benefit, only providing performance improvement for users with supporting browsers.

Given this graceful degradation, there's little reason to avoid the property when there's an opportunity to reduce rendering work during page load. With content-visibility now Baseline Newly available, you can use it to keep the initial rendering footprint as small as possible, leaving the browser with more time to respond to user interactions.