Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 139 ยท Best Practices

CSS Performance

Make CSS fast. Understand render-blocking stylesheets, inline critical CSS, skip selector myths, and speed up rendering with content-visibility and contain.

CSS rarely makes a page slow because of what a single rule does. It makes pages slow because of when it arrives and how much work it asks the browser to do. A large stylesheet that has to download before anything appears, a chain of @import requests, or a page with thousands of complex elements laid out at once: these are the real costs.

In this lesson you will learn how the browser turns CSS into pixels, why stylesheets block rendering and what to do about it, which "selector performance" advice is a myth, and two modern tools, content-visibility and contain, that let you skip work the user can't see yet.

How CSS becomes pixels

When a page loads, the browser roughly does this:

  1. Parse HTML into the DOM and CSS into a set of rules (the CSSOM).
  2. Style: match rules to elements and compute every property's value.
  3. Layout: work out the size and position of every box.
  4. Paint: fill in the pixels: text, colors, borders, shadows, images.
  5. Composite: combine painted layers into the final picture on screen.

After the first render, any change can send the browser back through some of these steps. Changing width triggers layout, then paint, then composite. Changing color skips layout. Changing transform or opacity can often skip layout and paint, which is why those are the properties to animate. Motion and Performance covers that side in detail.

Why CSS is render-blocking

A browser won't paint a page until it has downloaded and parsed every stylesheet that applies to it. That is intentional. If it painted first, the user would see a flash of unstyled content and then watch the page jump around.

So every <link rel="stylesheet"> in the <head> is render-blocking. The time it takes to fetch it adds directly to the time before the user sees anything. Practical consequences:

  • Keep the critical stylesheet small. Remove unused CSS. Old components, unused framework parts and duplicated rules all cost download and parse time.
  • Avoid @import chains. A stylesheet that imports another stylesheet can't request it until the first one arrives, so the downloads happen one after another instead of in parallel. Bundle files at build time, or use several <link> tags.
  • Compress and cache. Serve CSS with Brotli or gzip compression, and use a file name with a content hash (app.3f9c1a.css) so browsers can cache it for a long time.

The media attribute

A stylesheet whose media attribute doesn't match the current page is still downloaded, but at low priority and without blocking rendering:

HTML
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/css/print.css" media="print">
<link rel="stylesheet" href="/css/wide.css" media="(width >= 64rem)">

On a phone, wide.css doesn't hold up the first paint. The print styles you will write in the next lesson never block screen rendering.

Critical CSS

On content-heavy pages, a common technique is to inline critical CSS: put the few rules needed for the top of the page directly in a <style> element in the <head>, and load the full stylesheet without blocking:

HTML
<head>
  <style>
    /* only what the first screen needs: layout, header, hero, fonts */
    body { margin: 0; font-family: system-ui, sans-serif; }
    .site-header { display: flex; align-items: center; height: 4rem; }
  </style>

  <link rel="preload" href="/css/main.css" as="style"
        onload="this.onload = null; this.rel = 'stylesheet'">
  <noscript><link rel="stylesheet" href="/css/main.css"></noscript>
</head>

The first paint needs no extra request. It is a real gain on slow connections, but it adds build complexity and can cause a visible jump if the critical rules are wrong. Measure before and after. For a site with one modest, well-cached stylesheet, plain <link> is usually fine.

Selector performance: mostly a myth

You may read advice such as "never use the universal selector" or "descendant selectors are slow". Years ago this mattered a little. Modern browsers match selectors extremely fast, using indexes, caches and the trick of reading selectors from right to left: for .menu a, they first find a elements, then check for a .menu ancestor.

Run this experiment. It builds three thousand elements and compares a simple stylesheet with a deliberately complex one.

Timing simple vs complex selectors

Run it a few times. The numbers vary, but they are usually small and close together, and most of that time is layout, not selector matching. On a real site, the size of the DOM and the amount of layout work matter far more than how clever your selectors are. Write selectors for maintainability (low specificity, clear names), and let the browser worry about matching.

One genuine exception: changing a class high up in the tree, on body for example, can force the browser to recheck styles for the whole page. That is fine for a theme switch, but avoid doing it on every scroll event.

content-visibility: skip what's off screen

Long pages, such as feeds, documentation and comment threads, pay the full cost of laying out and painting content far below the fold. content-visibility: auto tells the browser it may skip rendering an element's contents while it is far from the viewport:

CSS
.article-section {
  content-visibility: auto;
  contain-intrinsic-size: auto 600px;
}

When the section scrolls near the screen, the browser renders it normally. Until then, it only reserves space. That is what contain-intrinsic-size is for: it gives the skipped element a placeholder size (here 600px tall). The auto keyword tells the browser to remember the real size once it has been rendered. Without a placeholder, skipped sections would collapse to zero height and the scrollbar would jump around.

content-visibility on a long list

Click each button a few times. With content-visibility: auto, the browser lays out only the posts near the visible area of the scroll box, so the layout time usually drops sharply. Scroll the feed: the posts render as they approach.

Support: content-visibility has worked in all major browsers since 2024. Browsers without it simply render everything as usual, so it is a safe progressive enhancement. Content skipped this way is still in the DOM, so find-in-page, links to #fragments and screen readers keep working.

Don't add it to everything. Use it on large, independent sections below the fold. On small elements, the bookkeeping costs more than it saves.

contain: promise the browser some isolation

content-visibility is built on a lower-level property, contain. It lets you promise that an element's insides don't affect the outside, so the browser can limit how much it recalculates when something inside changes:

  • contain: layout: the element's internal layout doesn't affect anything outside. It also becomes the containing block for absolutely and fixed positioned descendants.
  • contain: paint: descendants never paint outside the element's box. Anything that overflows is clipped, like overflow: clip.
  • contain: size: the element's size doesn't depend on its children. You must give it a size, or it collapses.
  • contain: style: counters and quotes inside don't leak out.
  • Shorthands: contain: content means layout, paint and style. contain: strict adds size.

Containment changes behavior, not just speed, so it is easy to see in action:

What contain changes

In the first widget, the badge has no positioned ancestor, so it flies to the top-right of the page. In the second, contain: layout makes the widget its containing block and contain: paint clips anything sticking out. Components that are truly self-contained, such as widgets, cards in a long list or ad slots, are good candidates. For the size-based version used by container queries, see Container Queries, which apply size containment through container-type.

Other habits that pay off

  • Load fonts carefully. Web fonts can hide text while they download. Use font-display: swap, WOFF2 files and only the weights you need. See Web Fonts.
  • Reserve space for media. Give images width and height attributes or an aspect-ratio so the layout doesn't shift when they load.
  • Animate the cheap properties. Prefer transform and opacity, and use will-change sparingly, only on elements about to animate.
  • Measure, don't guess. The Performance panel in DevTools shows style, layout and paint time. Lighthouse flags render-blocking resources and unused CSS. Fix what the measurements point at.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a normal <link rel="stylesheet"> in the head called render-blocking?

    Browsers delay the first paint until applicable stylesheets are downloaded and parsed.
  2. 2. What happens to <link rel="stylesheet" href="print.css" media="print"> on a screen?

    Stylesheets with non-matching media are still fetched, but they don't hold up the first paint.
  3. 3. What is the main purpose of contain-intrinsic-size next to content-visibility: auto?

    Skipped content would otherwise have no size. The placeholder keeps layout and scrolling stable.
  4. 4. Which statement about selector performance is most accurate today?

    Modern engines match selectors very efficiently, so choose selectors for clarity and maintainability.

Summary

  • CSS goes through style, layout, paint and composite; some changes skip steps.
  • Stylesheets block the first paint, so keep critical CSS small, avoid @import chains, compress and cache.
  • Non-matching media attributes make stylesheets non-blocking; inlining critical CSS can speed up the first paint.
  • Selector cost is rarely a real problem; write selectors for maintainability.
  • content-visibility: auto with contain-intrinsic-size skips rendering off-screen sections.
  • contain isolates an element's layout, paint, size or style, and changes positioning and clipping too.

Next: Print Styles, where you will make your pages look great on paper and in PDF exports.