Performance-Safe CSS: Avoiding Layout Shift, Managing Paint, and Shipping with Confidence
CSS performance techniques: prevent layout shift, animate compositor-friendly properties, use contain and content-visibility, and measure CLS and INP.
transform and opacity, isolate independent regions with contain and content-visibility, keep stylesheets small and early, and measure Cumulative Layout Shift (CLS), Largest Contentful Paint (LCP) and Interaction to Next Paint (INP) on real devices, not just your laptop.
A news article loads. You start reading the first paragraph, an ad slot expands above it, and the text jumps 250 pixels down the page. You find your place, a web font finishes loading, every line reflows, and the button you were about to tap moves under your thumb. Nothing here is a JavaScript bug. Every one of those shifts is a CSS decision that was never made.
Performance-safe CSS means styles that load without delaying the first render, do not move content after it appears, and keep each frame cheap enough to stay smooth. Google’s Core Web Vitals turn these into three numbers, each judged at the 75th percentile of real page loads: LCP should be 2.5 seconds or less, INP 200 milliseconds or less, and CLS 0.1 or less. Safari 26.2 added the APIs for measuring LCP and INP in December 2025, so those two are now measurable in every major browser; CLS is still reported only by Chromium.
My position: most CSS performance problems are not about clever optimizations. They are about missing information, such as an image without dimensions or a font without a fallback that matches its metrics. Give the browser sizes up front and most of the problem disappears.
How the browser turns CSS into pixels
Every frame can involve up to four stages, and the cost of a change depends on which stage it forces the browser to redo.
- Style: match selectors and compute values for affected elements.
- Layout: work out the size and position of every affected box.
- Paint: draw pixels for text, colors, borders, shadows and images into layers.
- Composite: combine layers on the GPU, applying transforms and opacity.
| Changing this | Triggers | Cost |
|---|---|---|
width, height, margin, padding, top, left, font-size, display |
Layout, paint, composite | Highest: can affect many other boxes |
color, background, box-shadow, border-radius, outline |
Paint, composite | Medium: redraws pixels, no geometry change |
transform, translate, scale, rotate, opacity |
Composite only, when on their own layer | Lowest: often handled off the main thread |
That table explains the most-repeated animation rule: animate transform and opacity, not layout properties.
Layout shift: reserve space for everything late
CLS measures how much visible content moves unexpectedly. Shifts within 500 milliseconds of a user interaction do not count, so a menu that pushes content when clicked is fine; content that moves on its own is not. Nearly every unexpected shift comes from something arriving after first paint without reserved space.
Images and video
<img src="chart.webp" width="1200" height="675" alt="Monthly signups chart">
img, video {
max-inline-size: 100%;
block-size: auto; /* keeps the aspect ratio from width and height attributes */
}
Browsers compute an aspect ratio from the width and height attributes before the image loads, so the space is reserved even in a fluid layout. If you cannot set attributes, set aspect-ratio: 16 / 9 in CSS. To find images on an existing page that are missing dimensions, I wrote a quick console script in finding images missing width and height in Chrome.
Ads, embeds and dynamic content
.ad-slot--leaderboard { min-block-size: 250px; } /* the most common size for this slot */
.embed--youtube { aspect-ratio: 16 / 9; }
.comments:empty { min-block-size: 20rem; } /* skeleton height while loading */
Reserve the most likely size. If the ad comes back smaller, the slot has some empty space, which is far better than content jumping. Never insert banners, cookie notices or “new posts” bars above content the user is already reading; overlay them or place them below.
Web fonts
When a web font replaces a fallback font with different metrics, every line can change width and height. Two tools fix it:
@font-face {
font-family: "Inter";
src: url("/fonts/inter-var.woff2") format("woff2");
font-display: swap; /* show text immediately in the fallback */
}
/* A fallback tuned to match Inter's metrics, so the swap barely moves text */
@font-face {
font-family: "Inter Fallback";
src: local("Arial");
size-adjust: 107%;
ascent-override: 90%;
descent-override: 22%;
line-gap-override: 0%;
}
body { font-family: "Inter", "Inter Fallback", system-ui, sans-serif; }
The values above are illustrative; generate real ones for your font with a tool such as Fontaine or Capsize, or let a framework’s font loader do it. size-adjust is supported in every major browser; check the override descriptors in Safari before relying on them. If the font is not essential to the brand, font-display: optional avoids the swap entirely on slow connections. Preload the one or two font files used above the fold with <link rel="preload" as="font" type="font/woff2" crossorigin>.
Scrollbars
When a page grows tall enough to scroll, the scrollbar appears and narrows the content on systems with classic scrollbars, shifting everything sideways. scrollbar-gutter: stable on the scrolling element reserves the space from the start.
Animation: stay on the compositor
/* WRONG: animates layout every frame */
.drawer { transition: left 300ms ease; left: -20rem; }
.drawer.is-open { left: 0; }
/* RIGHT: animates only on the compositor */
.drawer { transition: translate 300ms ease; translate: -100% 0; }
.drawer.is-open { translate: 0 0; }
The individual transform properties translate, scale and rotate are cross-browser and easier to combine than one long transform value. A few more rules:
- Never use
transition: all. It animates properties you did not intend, including layout properties, whenever any of them change. - Use
will-changesparingly. Settingwill-change: transformon an element that is about to animate promotes it to its own layer. Setting it on hundreds of elements wastes GPU memory and can make things slower. - Animate height without measuring. To expand an accordion smoothly, animate a grid track from
0frto1frrather thanmax-heightguesses. It works in every browser. Chromium’sinterpolate-size: allow-keywordslets you animate toheight: autodirectly, as an enhancement. - Respect
prefers-reduced-motion. Fewer animations is also less work.
.accordion__panel {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 250ms ease;
}
.accordion[open] .accordion__panel,
.accordion.is-open .accordion__panel { grid-template-rows: 1fr; }
.accordion__panel > div { overflow: hidden; }
Paint: know your expensive effects
Some effects are cheap once and expensive when repeated every frame:
- Large blurred shadows and
filter: blur()on elements that move or scroll. backdrop-filter, which must re-blur whatever is behind the element whenever that content changes, for example a frosted header over a scrolling page.background-attachment: fixed, which forces repaints while scrolling in many browsers.- Animated gradients and box-shadows, which repaint each frame. Animate the
opacityof a pseudo-element that holds the effect instead.
None of these is forbidden. Use the Rendering tab’s “Paint flashing” option in Chromium DevTools to see what actually repaints during scrolling and interactions, and fix what flashes constantly.
Containment: tell the browser what is independent
The contain property promises the browser that a subtree is independent, so changes inside it do not require re-laying out or repainting the rest of the page.
.widget {
contain: layout paint; /* internal changes stay internal; content is clipped to the box */
}
.comment {
content-visibility: auto;
contain-intrinsic-size: auto 12rem; /* estimated height until rendered, then remembered */
}
content-visibility: auto skips rendering work for elements that are off screen until they approach the viewport. On long pages such as comment threads, documentation and feeds, it can cut initial rendering time substantially. It has been supported in every major browser since 2024. The contain-intrinsic-size line matters: without an estimated size, skipped elements collapse to zero height and the scrollbar jumps as they render. The auto keyword tells the browser to remember the real size once an element has been rendered.
Containment has side effects worth knowing. contain: paint clips overflowing content, so dropdowns inside it get cut off unless they render in the top layer, as shown in the anchor positioning guide. It also makes the element a containing block for fixed descendants, the same trap described in the box model guide.
Style recalculation and interactions
INP measures how long the page takes to show the next frame after a click, tap or key press. Long style recalculation is a common cause of poor INP on large pages. Watch for:
- Toggling a class or custom property on
htmlorbody, which can force style recalculation for the entire document. Set state on the smallest element that needs it. - Broad
:has()rules anchored at the root, which can be re-evaluated on many DOM changes. The :has() guide covers how to keep them narrow. - Very large DOMs. Style and layout cost grows with element count.
content-visibilityhelps; fewer wrapper elements help more. - Layout thrashing in JavaScript: reading
offsetHeightafter writing styles, in a loop, forces repeated synchronous layouts. Batch reads before writes.
Loading CSS without blocking the first render
- Stylesheets in the head block rendering until they download. Keep the critical stylesheet small, and inline truly critical rules for the first screen on content-heavy sites.
- Avoid
@importchains in production. Each import is discovered only after its parent file downloads. Bundle, or use parallel<link>tags. - Use
mediaattributes for conditional sheets, such asmedia="print", so they do not block screen rendering. - Remove unused CSS. The Coverage panel in Chromium DevTools shows how much of each stylesheet the page actually uses.
- Do not hide the page until JavaScript runs. Anti-flicker snippets that set
opacity: 0onbodyfor A/B testing tools directly delay LCP.
Shipping with confidence
Performance regressions return unless something catches them. A light process is enough:
- Measure real users. Field data from the
web-vitalsJavaScript library or the Chrome User Experience Report shows what lab tests miss, such as slow phones and long sessions. - Test in the lab on throttled devices. Use DevTools CPU throttling and a mid-range Android device. Your development laptop is not your users’ phone.
- Visualize shifts. The Rendering tab’s “Layout Shift Regions” option highlights every shift as it happens.
- Automate checks in CI. Run Lighthouse CI against key templates with budgets for CLS, LCP and total CSS size, and fail the build when a change crosses them.
- Lint the obvious. Stylelint rules can forbid
transition: alland flag layout properties insidetransitionand@keyframes.
Frequently Asked Questions
How does CSS cause layout shift?
Layout shift happens when content appears or changes size after first paint without reserved space: images and embeds without dimensions, ads and banners inserted above content, and web fonts that swap in with different metrics. Reserve space with width and height attributes, aspect-ratio, min-height and metric-matched fallback fonts.
Which CSS properties are cheapest to animate?
transform, including the individual translate, scale and rotate properties, and opacity. They can usually be handled by the compositor without repeating layout or paint. Properties like width, height, top, left and margin trigger layout on every frame and are the most expensive.
What does content-visibility: auto do?
It lets the browser skip rendering work for an element while it is off screen, rendering it only as it approaches the viewport. Pair it with contain-intrinsic-size: auto and an estimated size so off-screen sections keep a sensible height and the scrollbar does not jump.
What are good Core Web Vitals scores?
Google considers a page good when, at the 75th percentile of page loads, Largest Contentful Paint is 2.5 seconds or less, Interaction to Next Paint is 200 milliseconds or less, and Cumulative Layout Shift is 0.1 or less.
Give the browser the facts early
Fast CSS is mostly honest CSS: tell the browser how big things will be, which parts are independent, and which properties will move. Do that, keep animations on the compositor, and let CI catch regressions before your users do. If you are deciding how much of this to hand to a framework, vanilla CSS vs. Tailwind in 2026 works through that choice.
Rule of thumb: if something loads late, its space should not.
Originally posted on 9 July 2026 and post last modified on 9 July 2026