CSS Performance: Selectors, @import and Layout Cost
Ship less CSS, keep selectors flat, split CSS per template, use link instead of @import, and measure selector and layout cost with live benchmarks.
Related chapters
- Core Web Vitals in Production: LCP, INP and CLS
- The Cost of JavaScript: Bundle Size, Parsing and Hydration
- Critical Rendering Path Explained: DOM, CSSOM, Paint
- Critical CSS: Inline Above-the-Fold Styles
- HTTP Caching Explained: Cache-Control, ETag, CDN
- Lazy Loading Images and Code: Best Practices
- List Virtualization (Windowing) in React Explained
- Intersection Observer API Explained, with Examples
- How Mobile Browsers Work: Camera, Permissions, Quirks
- Frontend Performance Case Studies: Netflix, Airbnb, Flipkart
Keep learning
Overview
Chapter 73 · css performance Every CSS byte blocks the first paint. Every rule is matched against every element. CSS is cheap to write and expensive to ship. Send less of it, send only what this page needs, load it in parallel, and keep selectors and animations easy for the browser.
8. What you decide in production
Find unused CSS first Coverage tab: 70 percent of a framework stylesheet unused on this page. used 30% unused on this page DevTools Coverage shows which rules matched during a session. PurgeCSS, uncss, or Tailwind’s content scan remove the rest at build time. Safelist classes added by JavaScript (an .is-open modal) or they vanish. Prune the framework Import only the framework modules the site uses: grid, buttons, forms. Skip tables, print, carousel. Import a framework’s source modules instead of its full build: Bootstrap’s Sass partials, Tailwind’s generated output. Every component you do not use is a rule every element is tested against. Override with the longhand Overriding one side of a shorthand copy margin: 20px 20px 0 20px to change one side margin-bottom: 0 in the new context Shorthand saves bytes in the base rule. When one context changes one side, override that side with the longhand. A copied shorthand silently stops inheriting future changes. CSS in the head, never @import A stylesheet at the end of the body paints raw content first, then re-styles the whole page. end of body <link> in the <head>, discovered by the preload scanner, fetched in parallel. In plain CSS, @import is found only after its parent downloads. Sass and Less @use/@import are fine: they bundle at build time. Transitions before libraries Animation choices transition: transform .2s, zero bytes a JS animation library for a hover effect For hovers, drawers and modals, a CSS transition on transform or opacity costs no download and no script time. Keep JavaScript animation for physics, sequencing and scroll-linked work. Contain the blast radius Without containment a change re-lays out the whole page. With contain: content only the widget is re-laid out. no contain whole document widget only contain: content tells the browser a widget’s layout and paint cannot affect the rest of the page. content-visibility: auto skips rendering off-screen sections until they are near. Minify, compress, hash Source CSS, minified, Brotli-compressed, hashed name, cached for a year. 42 KB src 30 KB min Budget the first-paint CSS Render-blocking CSS against a budget. blocking CSS new carousel Track render-blocking CSS per template in CI, the same way you track JavaScript. CSS grows by append: nobody deletes a rule they are not sure about. A real small-business stylesheet: verbose properties, deep selectors, repeated declarations. margin, padding, border, background, border-radius, font: one property instead of four. 28% smaller. Shallow selectors + unused rules removed Select only what is needed to match the element, then strip rules no page uses. Another 38%. DRY: merge repeated declarations A redundancy finder (csscss) listed three selectors sharing 12 declarations. Merged: another 10%.
1. Write less CSS: a 60% diet with no new tools
A case study from Web Performance in Action: the same site, same look, four passes over its stylesheet. Diet step Total: 18.5 KB → 7.42 KB, about 60% less, page unchanged.
2. Nesting is free to write and paid for in the output
Sass, Less and native CSS nesting mirror the HTML. The compiled selector carries every level: more bytes, more matching work, and specificity you will have to beat later. per rule specificity (id, class, tag) ancestors checked per match Shallow output: short, cheap to match, easy to override.
3. Ship each page the CSS for its template
Analytics says 100 visitors land on home, 20 go on to a recipe, 5 reach search. One bundle makes all 100 pay for search. Global + per template Visitor flow: 100 on home, 20 continue to recipe, 5 to search. first page recipe + search, unused CSS sent to 100 visitors Landing pays only for what it shows. A recipe page adds its own 10 KB, once, and global stays cached. Everything is cached after the first page, which only helps the 20% who go further. ↳ @import fonts.css found late ↳ @import grid.css app.css (all three) app.css (in footer) Main thread Unstyled flash Styled paint
4. @import waits in line; <link> goes in parallel
The browser can only fetch a stylesheet it has discovered. Change where the CSS is declared. Declare the CSS @import inside CSS 3 × <link> 1 bundled <link> <link> at end of body unstyled flash fonts.css and grid.css are invisible until styles.css arrives. One extra round trip per level of @import. All three are in the HTML, so the preload scanner starts them together. One round trip. The page paints unstyled (flash of unstyled content), then the stylesheet forces style, layout and paint of the whole document again. section ul li section > ul > li div.wrap section.col ul.list li.item section:has(.item) li
5. Measure it here: selectors and layout on {ITEMS.toLocaleString()} elements
Benchmark 9 selectors Benchmark 3 layout engines Selector benchmark results Press “Benchmark 9 selectors”. Layout benchmark results inline-block + width Press “Benchmark 3 layout engines”. The 2016 benchmark this lesson is based on found most selectors similar and sibling, pseudo-class and attribute selectors slowest. See what your browser does today. 80 decl. @media (min-width) 150 decl. @media (max-width) undo 180 decl. 120 decl.
6. Mobile-first: the weakest device does the least work
Desktop-first CSS makes the phone apply the desktop layout and then undo it. Mobile-first starts simple and adds complexity as the screen grows. Write the base styles for Mobile first (min-width) Desktop first (max-width) <meta name="viewport" content="width=device-width,initial-scale=1"> Declarations processed per device The phone renders the mobile layout at its own width. Without the viewport tag the phone renders a 980 pixel desktop page shrunk to fit. phone layout 980px page, shrunk The phone matches 120 desktop declarations and then 60 more to undo them, on the device with the slowest CPU. Without the viewport tag, the phone pretends to be 980px wide: no breakpoint matches and the page is shrunk to fit. Never disable zoom in that tag. too late nav hovered set → removed every element one layer each slower overall The browser discovers on the first frame that the link needs its own layer. That frame does extra work and can stutter. The hint is set at the same moment as the change, so the browser has no time to prepare. Same stutter, plus a rule that looks like it helps. Hovering the nav comes before hovering a link. The layer is ready by the time the transition starts. Set the hint on intent (pointer enters, modal opens), remove it when the animation ends. Precise, and memory is returned. Every element asks for its own layer. Memory balloons and compositing slows down. This is the hint used as a hammer.
7. will-change is a forecast, so give it time
Where the hint lives No hint On a:hover On .nav:hover a Set by JS on intent enter nav hover link
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.