Using content-visibility for Performance Optimization

This is a "Today I Learned" post - a quick note about something I discovered.
Topic: css

Today I learned about the CSS content-visibility property, which can dramatically improve page rendering performance by skipping rendering for off-screen content!

The problem it solves

Rendering large webpages with lots of content can be slow, especially on mobile devices. Even content that’s way off-screen (that users can’t see yet) takes processing power to render, slowing down the initial page load.

Basic usage

.section {
  content-visibility: auto;
  contain-intrinsic-size: 0 500px;
}

The content-visibility: auto tells the browser to skip rendering this element if it’s off-screen. The contain-intrinsic-size property provides an estimated size so the browser can allocate space before it renders the content.

Practical example

Here’s how you might use it for a long-scrolling page with multiple sections:

🦒

Giraffe Section

This section has complex content that won't render until you scroll to it!

Box 1
Box 2
Box 3
🐘

Elephant Section

Another section with complex content that won't render until visible!

Box 1
Box 2
Box 3
🦁

Lion Section

Yet another section with complex content saved from rendering!

Box 1
Box 2
Box 3
🐼

Panda Section

The browser is saving resources by not rendering this until needed!

Box 1
Box 2
Box 3
.animal-section {
  content-visibility: auto;
  contain-intrinsic-size: 0 200px;
}

Try scrolling through the sections above! The browser only renders each section as it comes into view.

Important considerations

  1. Layout shifts: Without proper contain-intrinsic-size values, you might get layout shifts as content comes into view. Always provide reasonable size estimates.

  2. Search engines: Content with content-visibility: auto is still accessible to search engines, but consider the impact on critical content.

  3. Alternative for older browsers: You can use feature detection in CSS:

@supports (content-visibility: auto) {
  .section {
    content-visibility: auto;
    contain-intrinsic-size: 0 500px;
  }
}

Performance impact

On pages with lots of content, content-visibility can reduce initial rendering time by 50% or more! It’s especially useful for long-scrolling pages like infinite feeds, blog posts with many images, or complex dashboards.