Sub topic 13
Bundling, splitting and delivering CSS
This chapter assumes you know the cascade and @layer, BEM or CSS Modules naming, and a folder structure like the one from the file-organisation chapter. You should also be comfortable running npm scripts. The earlier chapters cover how to write and organise CSS. This one covers how that CSS gets from your src/ folder to the browser, and how the delivery choices can change how your styles behave.
Why delivery is part of architecture
CSS is render-blocking. The browser will not paint a page until it has downloaded and parsed every stylesheet linked in the <head> that applies to the current screen. A well-organised codebase with 40 small files can still load slowly if each file is a separate request. It can also break if those files arrive in the wrong order.
Delivery has three goals:
- Ship as few bytes as possible.
- Ship them in as few blocking requests as possible.
- Keep the cascade order the same as the one you designed.
The third goal is the one people forget. Order is part of your CSS, so bundling and splitting must not change it.
What a build step does to CSS
A typical CSS build runs these stages in order:
- Resolve imports. Each
@importis replaced by the contents of the file it names. - Transform. Tools such as PostCSS or Lightning CSS add vendor prefixes and compile modern syntax for your browser targets. CSS Modules also rewrites class names here.
- Minify. Whitespace and comments are removed and values are shortened.
- Extract and hash. The result is written to
.cssfiles whose names include a hash of their contents.
Why not use native `@import` in production?
A browser that meets @import in a stylesheet must download the first file before it learns about the second. Nested imports form a request chain, and each link adds a full round trip. Resolving imports at build time avoids this. Native @import is fine for development servers, but production output should have none of it.
Keeping layer order through the bundle
If you use @layer, declare the order once at the very top of your entry file. A @layer statement is allowed before @import, so the order is fixed before any imported file is read.
/* src/main.css */
@layer reset, base, components, utilities;
@import "./reset.css" layer(reset);
@import "./base.css" layer(base);
@import "./components/card.css" layer(components);
@import "./components/button.css" layer(components);
@import "./utilities.css" layer(utilities);Here is a minimal PostCSS setup that inlines these imports and minifies the result.
// postcss.config.js
module.exports = {
plugins: [
require("postcss-import"),
require("cssnano")({ preset: "default" })
]
};{
"scripts": {
"build:css": "postcss src/main.css --output dist/main.css"
},
"devDependencies": {
"cssnano": "^7.0.0",
"postcss": "^8.4.0",
"postcss-cli": "^11.0.0",
"postcss-import": "^16.0.0"
}
}Run npm install and then npm run build:css. Open dist/main.css and check that the @layer reset, base, components, utilities; statement is still first. After any minifier upgrade, check that rules were not merged across layer boundaries. Merging rules from different layers changes which declaration wins.
Splitting CSS
A single bundle is simple, but every page then pays for styles it never uses. Splitting divides the CSS into several files. There are three common strategies.
| Strategy | What is split | Good for | Main risk |
|---|---|---|---|
| One global bundle | Nothing | Small sites, marketing pages | Large file as the site grows |
| Per route | One file per page or route | Multi-page apps and frameworks with routers | Shared styles duplicated or fetched twice |
| Per component | One file per component, loaded with its JavaScript | Component frameworks with CSS Modules | Cascade order between chunks |
Most projects settle on a hybrid. A small global file holds the layer declaration, reset, tokens and base styles. Route or component files hold the rest.
Splitting with a bundler
Bundlers such as Vite, webpack and Rollup split CSS automatically when a component imports its own stylesheet. In Vite, CSS code splitting is on by default. The config below makes the behaviour explicit and sets readable scoped class names for CSS Modules.
// vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
build: {
cssCodeSplit: true
},
css: {
modules: {
generateScopedName: "[name]__[local]___[hash:base64:5]"
}
}
});A component then imports its module file. The bundler puts that CSS in a chunk tied to the component's JavaScript.
// Button.js
import styles from "./Button.module.css";
export function createButton(label) {
const button = document.createElement("button");
button.className = styles.root + " " + styles.primary;
button.textContent = label;
return button;
}The Button.module.css file from the scoping chapter works unchanged. The class .root becomes something like Button-module__root___x9Ab2, so it cannot collide with another .root.
The order problem
When CSS is split, the order in which chunks load can differ between pages. Suppose card.css and button.css both set padding on an element with two equal-specificity selectors. Page A loads card first and page B loads button first. The same markup now renders differently on each page. The bug is hard to spot because each page looks correct in isolation.
Three habits prevent this:
- Keep specificity low and equal, as BEM does, so that components rarely compete.
- Put anything that must win in a later
@layer, so layer order decides instead of file order. - Never rely on one component's CSS overriding another component's CSS. If two components need to interact, make the relationship explicit with a modifier or a custom property.
Delivering CSS to the browser
Critical CSS and non-blocking styles
Critical CSS is the smallest set of rules needed to render the first screen. You can inline it in a <style> element in the <head> and load the rest normally. This removes a blocking request from the first paint. The cost is that the inlined bytes are not cached separately, so keep this part small, usually a few kilobytes.
A simpler technique uses the media attribute. A stylesheet whose media query does not match is still downloaded, but it does not block rendering.
<link rel="stylesheet" href="/assets/main.3f9a1c.css">
<link rel="stylesheet" href="/assets/print.a81b2d.css" media="print">The print stylesheet never delays the screen render. Use this for print styles and for large, conditional styles such as wide-screen layouts, where media="(min-width: 80rem)" applies.
Caching with content hashes
Hashed file names let you cache aggressively. If the contents change, the name changes, so users never receive a stale file under an old name. Serve hashed files with a long lifetime.
Cache-Control: public, max-age=31536000, immutableThe HTML page that links the CSS should not be cached this way. It must be revalidated so it can point to the new hashed names after a deploy.
Compression and protocol
Compress CSS with Brotli, or gzip as a fallback. CSS compresses well because it is repetitive, and Brotli commonly cuts it by around 80 percent. HTTP/2 and HTTP/3 make several parallel requests cheaper than they were on HTTP/1.1. That favours splitting, but it does not remove the cost of a long chain of dependent requests.
Measuring what you ship
Do not guess which CSS is unused or too large. Measure it.
- Build output: compare file sizes before and after each change. Check both raw and compressed sizes.
- Chrome DevTools Coverage panel: load a page and see what percentage of each stylesheet was used. A global bundle with 10 percent usage on most pages is a signal to split.
- Lighthouse or WebPageTest: look for render-blocking resources and the effect on first contentful paint.
Coverage numbers describe one page state. Styles for hover, dialogs and other states may show as unused, so check across several states before deleting anything. The refactoring chapter covers safe removal.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Native `@import` left in production CSS | Waterfall of sequential requests, slow first paint | Inline imports at build time |
| Layer order not declared first | Utilities lose to components after bundling | Put the `@layer` order statement at the top of the entry file |
| Relying on file order between chunks | Styles differ between pages | Use layers and low, equal specificity |
| Inlining too much critical CSS | HTML grows, no caching of styles | Inline only above-the-fold rules |
| Long cache lifetime on unhashed names | Users see old styles after deploy | Hash file names or shorten the lifetime |
| Trusting minifier output without checking | Rules merged across layers | Diff the output and test key pages |
Putting it together
A reasonable default for a mid-sized application:
- Declare layer order in one entry file.
- Bundle reset, tokens and base styles into a global file.
- Let the bundler split component CSS by route.
- Minify, hash and compress the output.
- Serve hashed files with
immutablecaching. - Check Coverage and page-load metrics on every release, and adjust the splits when numbers drift.
Exercise
Two components, loaded in separate CSS chunks, both use a single class selector to set margin-top on the same element. Page A shows 1rem and page B shows 2rem. What is the cause, and give two ways to fix it.
Show answer
The selectors have equal specificity, so source order decides, and the chunks load in a different order on each page. Fix it by removing the overlap, for example by giving one component a modifier that sets the value explicitly, or by putting the style that must win in a later @layer so that layer order decides instead of file order.
Exercise
Your entry file contains @import "./card.css" layer(components); followed by @layer reset, base, components, utilities;. After bundling, utilities no longer override components. What is wrong, and how do you correct it?
Show answer
The layer order statement comes after the import, so the components layer is created first and the declared order is applied late or inconsistently. Move @layer reset, base, components, utilities; to the first line of the file, before any @import, so the order is fixed before any layer content is read.
Exercise
A hashed file main.3f9a1c.css is served with Cache-Control: max-age=31536000, immutable, but the HTML page that links to it is served with the same header. What goes wrong after a deploy?
Show answer
Browsers keep using the cached HTML for up to a year, so they keep requesting the old hashed CSS file name and never see the new one. The HTML must be revalidated (for example no-cache) so it can point at the new hashed file names.