Frontend development · Intermediate · 18 min
Organise CSS with cascade layers
By Padding · Updated 18 Nov 2026
Modern browsers · CSS Cascading and Inheritance Level 5 · checked in Chromium 159 · Node.js 26
You will have a stylesheet for the Larkfield Clinic booking app split into reset, tokens, base, vendor, layout, components and utilities layers, a third-party widget that can no longer override your components, no !important left, and a Playwright script that checks the computed styles.
On this page
Every stylesheet that grows long enough ends up in a specificity fight. A base rule for links beats a button class because a:link has one more selector part. A third-party widget ships .widget button and quietly wins over your own components. The usual fixes, longer selectors or !important, each make the next fight worse.
Cascade layers change the rules of that fight. You name a few layers and put them in order once, at the top of the file. When two declarations from different layers compete, the later layer wins, whatever the specificity of the selectors. Specificity still decides between rules inside the same layer, which is where it belongs.
In this tutorial you take one screen of the Larkfield Clinic booking app, Pick a time, with a stylesheet that has both kinds of fight: a calendar widget that overrides the day buttons, and a Continue link that only looks right because of two !important flags. You rebuild the stylesheet in seven layers, pull the widget's CSS into a layer of its own, remove every !important, and finish with a Playwright script that checks the computed styles in a real browser. The colour and spacing values are the Larkfield tokens from Turn design tokens into CSS custom properties. You do not need to have done that tutorial first.
Step 1 · Create the page and its current stylesheet
Make a folder with three files: the page, the calendar widget's stylesheet and the app's own stylesheet as it stands today. The widget, called tidy-calendar here, is a stand-in for any third-party component you install from npm or a CDN: a date picker, a carousel, a cookie banner. It renders the week strip as a list with the class tc-week and lets you add your own class, day, to each day button.
mkdir -p ~/layers-demo/vendor
cd ~/layers-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pick a time · Larkfield Clinic</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main class="screen">
<header>
<h1>Pick a time</h1>
<p class="muted">Nurse appointment, 15 min</p>
</header>
<section aria-labelledby="week">
<h2 id="week">Week of 8 December</h2>
<ul class="tc-week">
<li><button class="day" type="button" aria-pressed="false">Mon 8</button></li>
<li><button class="day" type="button" aria-pressed="true">Tue 9</button></li>
<li><button class="day" type="button" aria-pressed="false">Wed 10</button></li>
<li><button class="day" type="button" aria-pressed="false">Thu 11</button></li>
<li><button class="day" type="button" aria-pressed="false">Fri 12</button></li>
</ul>
</section>
<p class="muted">Chosen: Tuesday 9 December, 10:30. No time that suits you? <a href="#call">Call the clinic</a></p>
<div class="actions">
<a class="button-primary u-full-width" href="#details">Continue</a>
</div>
</main>
</body>
</html>
HTML
cat > vendor/tidy-calendar.css <<'CSS'
/* tidy-calendar 2.4: a stand-in for a third-party widget stylesheet */
.tc-week { display: flex; gap: 2px; list-style: none; padding: 0; margin: 0; }
.tc-week button {
font: inherit;
padding: 4px 6px;
border: 1px solid #cccccc;
border-radius: 0;
background: #eeeeee;
color: #333333;
}
.tc-week button[aria-pressed="true"] { background: #3366cc; color: #ffffff; }
CSS
cat > styles.css <<'CSS'
@import url("vendor/tidy-calendar.css");
*, *::before, *::after { box-sizing: border-box; }
body, h1, h2, p, ul { margin: 0; }
body { font-family: system-ui, sans-serif; line-height: 1.5; color: #1b1f24; background: #f6f7f8; }
a:link, a:visited { color: #0f5e5a; text-decoration: underline; }
.screen { max-width: 30rem; margin: 0 auto; padding: 1rem; display: grid; gap: 1rem; }
.muted { color: #5a6270; }
.day { padding: 0.75rem; border: 1px solid #7d8592; border-radius: 0.5rem; background: #ffffff; color: #1b1f24; }
.day[aria-pressed="true"] { background: #0f5e5a; border-color: #0f5e5a; color: #ffffff; }
.button-primary {
display: inline-block;
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
background: #0f5e5a;
color: #ffffff !important; /* loses to a:link without this */
text-decoration: none !important; /* same */
font-weight: 600;
}
.u-full-width { display: block; width: 100%; text-align: center; }
CSSLook at the two losing rules and count their specificity, written as (IDs, classes, elements). The widget's .tc-week button is (0, 1, 1): one class and one element. The app's .day is (0, 1, 0). The widget wins on padding, border, corners and colour, even though the app's stylesheet comes later. Its selected rule, .tc-week button[aria-pressed="true"], is (0, 2, 1) against the app's (0, 2, 0), so the selected day is the widget's blue, not Larkfield teal.
The Continue link has the same problem the other way round. a:link is (0, 1, 1), because a pseudo-class counts like a class, and it beats .button-primary at (0, 1, 0). Without the two !important flags the button text would be teal on a teal background, invisible.
Check it worked
Open index.html in a browser (drag it into a window, or run open index.html on macOS or xdg-open index.html on Linux). The week strip has square grey day buttons packed 2 pixels apart, and Tue 9 is bright blue. That is the widget's look, not Larkfield's. The Continue button is teal with white text and spans the width of the screen. Run grep -c '!important' styles.css and it prints 2.
Step 2 · Declare the layer order and import the widget into a layer
Keep the old file for comparison and start a new styles.css. Its first rule is a layer statement: a list of layer names, lowest priority first. Writing the order before any styles means the order is fixed in one place, and a block added to a layer later in the file, or in another file, still sits at the position this line gives it.
cd ~/layers-demo
mv styles.css old-styles.css
cat > styles.css <<'CSS'
/* Larkfield booking app. Layer order, lowest priority first. */
@layer reset, tokens, base, vendor, layout, components, utilities;
@import url("vendor/tidy-calendar.css") layer(vendor);
CSSEach layer has one job:
resetremoves browser defaults you do not want, such as margins on headings.tokensholds the custom properties for colour, spacing and radius.basestyles bare elements: the body, headings and links.vendorholds third-party CSS. It sits above base, so a widget can restyle bare elements, and below everything you write for the app.layoutplaces things: the screen width, gaps and how a row wraps.componentsstyles named parts of the interface, such as the day buttons and the primary button.utilitiesholds single-purpose classes that should beat a component when you add them to it.
The layer(vendor) part of the @import puts every rule in the widget's file into the vendor layer without editing that file, so an update from the widget's authors keeps working. An @import has to come before any other rule in a stylesheet. The @layer statement is one of the few things allowed above it.
A note on performance. Every @import is one more request, made only after the first stylesheet has arrived. On slow mobile connections, and for readers paying for prepaid data, that extra round trip is noticeable. Use it as it is here while you develop, then let your build tool combine the files for production. Check that your bundler keeps layer() on imports; most current ones do, but read their documentation rather than assume.
Check it worked
Reload the page. Everything except the week strip has lost its styling: the page background is white, the text is in the browser's default font and Continue is a plain underlined link. The week strip still looks like the widget, square grey buttons and a blue Tue 9, which shows the import worked.
Step 3 · Move the reset, tokens and base styles into layers
Append the first three layers. A layer block, @layer name { ... }, adds rules to a layer that already has a place in the order. The token values replace the raw hex codes from the old file; they are a subset of the Larkfield tokens, with primitives first and semantic tokens pointing at them.
cd ~/layers-demo
cat >> styles.css <<'CSS'
@layer reset {
*, *::before, *::after { box-sizing: border-box; }
body, h1, h2, p, ul { margin: 0; }
}
@layer tokens {
:root {
/* primitives */
--grey-0: #ffffff;
--grey-50: #f6f7f8;
--grey-500: #7d8592;
--grey-600: #5a6270;
--grey-900: #1b1f24;
--teal-700: #0f5e5a;
--space-8: 0.5rem;
--space-12: 0.75rem;
--space-16: 1rem;
--space-24: 1.5rem;
--radius-8: 0.5rem;
/* semantic tokens */
--colour-text: var(--grey-900);
--colour-text-muted: var(--grey-600);
--colour-surface: var(--grey-0);
--colour-canvas: var(--grey-50);
--colour-border: var(--grey-500);
--colour-accent: var(--teal-700);
--colour-on-accent: var(--grey-0);
--space-stack-s: var(--space-8);
--space-stack-m: var(--space-16);
--space-stack-l: var(--space-24);
--space-inset-screen: var(--space-16);
--space-inset-control: var(--space-12);
--radius-control: var(--radius-8);
}
}
@layer base {
body {
font-family: system-ui, sans-serif;
line-height: 1.5;
color: var(--colour-text);
background: var(--colour-canvas);
}
h1 { font-size: 1.75rem; line-height: 1.2; }
h2 { font-size: 1.125rem; }
a:link, a:visited {
color: var(--colour-accent);
text-decoration: underline;
text-underline-offset: 0.15em;
}
}
CSSPutting custom properties in a layer does not change how var() reads them. The layer only matters if two rules set the same custom property on the same element, which is exactly the clash you want the order to settle.
Check it worked
Reload. The background is a very light grey, the headings are bold and sized, and the body text uses your system font. Continue is still an underlined teal link, because no component styles it yet, and the week strip still looks like the widget: the vendor layer is above base, so it is meant to win over these rules.
Step 4 · Add layout and components, and watch layer order beat specificity
Now the two layers that were losing their fights. Append them, with no !important anywhere:
cd ~/layers-demo
cat >> styles.css <<'CSS'
@layer layout {
.screen {
max-width: 30rem;
margin-inline: auto;
padding: var(--space-inset-screen);
display: grid;
gap: var(--space-stack-m);
}
.tc-week { flex-wrap: wrap; gap: var(--space-stack-s); }
.actions { padding-block-start: var(--space-stack-s); }
}
@layer components {
.muted { color: var(--colour-text-muted); }
.day {
font: inherit;
padding: var(--space-inset-control);
border: 1px solid var(--colour-border);
border-radius: var(--radius-control);
background: var(--colour-surface);
color: var(--colour-text);
}
.day[aria-pressed="true"] {
background: var(--colour-accent);
border-color: var(--colour-accent);
color: var(--colour-on-accent);
}
.button-primary {
display: inline-block;
padding: var(--space-inset-control) var(--space-stack-l);
border-radius: var(--radius-control);
background: var(--colour-accent);
color: var(--colour-on-accent);
text-decoration: none;
font-weight: 600;
}
}
CSSNothing about the selectors changed. .day is still (0, 1, 0) against the widget's (0, 1, 1), and .button-primary is still (0, 1, 0) against a:link at (0, 1, 1). What changed is that the browser compares layers before it looks at specificity. components comes after vendor and base in the order statement, so its declarations win, and the specificity of the losing selectors is never consulted.
The layout layer does the same to the widget's spacing. .tc-week sets a wider gap and lets the days wrap onto a second row on narrow phones, overriding the widget's gap: 2px without touching its file. Properties you do not override, such as the widget's display: flex and list-style: none, still apply: a layer lowers the widget's priority, it does not remove its styles.
Check it worked
Reload. The day buttons are white with a grey border and rounded corners, 8 pixels apart, and Tue 9 is Larkfield teal with white text. Continue is a teal button with white, un-underlined text. Run grep -c '!important' styles.css and it prints 0. In Chrome or Edge, open DevTools (F12), select Tue 9 in the Elements panel and look at the Styles pane: the rules are grouped under their layer names, and the widget's background from the vendor layer is struck through below the components rule.
Step 5 · Add utilities and learn the two exceptions
Utilities come last, so a utility class beats any component it is added to. The Continue link carries u-full-width so it fills the screen on a phone, which is easier to tap with a thumb:
cd ~/layers-demo
cat >> styles.css <<'CSS'
@layer utilities {
.u-full-width { display: block; width: 100%; text-align: center; }
}
CSS.u-full-width and .button-primary have the same specificity, (0, 1, 0). Without layers, whichever came later in the file would win, and moving a rule would break the page. With layers, utilities win because of the order statement, wherever the block sits in the file.
Two rules of the cascade surprise people. Keep them in mind before you add anything else to this file.
Styles outside any layer beat every layer. A rule written in styles.css without an @layer block around it, or in a stylesheet loaded without one, sits above utilities. That is useful for a short-lived override while you debug, and a trap when a colleague pastes a quick fix at the end of the file and it quietly wins over everything. In this project, keep every rule inside a layer. The only things outside one are the order statement and the import.
!important reverses the order. An important declaration in an early layer beats an important declaration in a later one, so !important in reset would beat !important in utilities. This is deliberate: it lets a low layer protect something, such as an accessibility setting, from everything above it. It also means !important is not a way to climb the order. If you find yourself reaching for it, the rule is probably in the wrong layer.
One more point for older devices. Chrome and Edge 99, Firefox 97 and Safari 15.4, all released in 2022, were the first versions to support cascade layers. A browser older than that ignores every @layer block, so the page arrives unstyled. Most phones update their browser through the app store, but if your analytics show many visits from old Android browsers that never update, test on one before shipping, or serve a flat fallback stylesheet to them.
Check it worked
Reload the page. Continue now spans the full width of the screen with its text centred. In DevTools, select Continue: in the Styles pane, the display: block from .u-full-width in the utilities layer is active and the display: inline-block from .button-primary in the components layer is struck through.
Step 6 · Test the computed styles with Playwright
Looking at the page proves it works today. A test proves it still works after the next widget update or the next refactor. Playwright opens the page in a real browser engine and reads the styles the browser computed, which is the only result that counts.
Install it in the demo folder. The second command downloads Chromium and, on Linux, the system libraries it needs:
cd ~/layers-demo
npm init -y > /dev/null
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromiumWrite the check. It reads styles.css for the layer order and any !important, then opens the page at phone width and checks one computed value for each fight you fixed:
cd ~/layers-demo
cat > check-layers.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
// 1. The source: one order statement first, and no !important.
const source = await readFile('styles.css', 'utf8');
const order = source.match(/@layer\s+([\w\s,-]+);/)[1].split(',').map((name) => name.trim());
assert.deepEqual(order, ['reset', 'tokens', 'base', 'vendor', 'layout', 'components', 'utilities']);
assert.ok(!source.includes('!important'), 'styles.css contains !important');
// 2. The result: computed styles at phone width.
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 400, height: 800 } });
await page.goto(pathToFileURL('index.html').href);
const style = (selector) => page.$eval(selector, (el) => {
const s = getComputedStyle(el);
return { bg: s.backgroundColor, colour: s.color, radius: s.borderTopLeftRadius,
line: s.textDecorationLine, display: s.display, gap: s.columnGap, width: el.getBoundingClientRect().width };
});
const selected = await style('.day[aria-pressed="true"]');
assert.equal(selected.bg, 'rgb(15, 94, 90)', 'components beat vendor: selected day is teal');
assert.equal(selected.radius, '8px', 'components beat vendor: rounded corners');
const plain = await style('.day[aria-pressed="false"]');
assert.equal(plain.bg, 'rgb(255, 255, 255)', 'components beat vendor: plain day is white');
const week = await style('.tc-week');
assert.equal(week.display, 'flex', 'vendor styles still apply where not overridden');
assert.equal(week.gap, '8px', 'layout beats vendor: wider gap');
const button = await style('.button-primary');
assert.equal(button.colour, 'rgb(255, 255, 255)', 'components beat base: white text without !important');
assert.equal(button.line, 'none', 'components beat base: no underline');
assert.equal(button.display, 'block', 'utilities beat components: full width');
const screen = await style('.screen');
assert.equal(Math.round(button.width), Math.round(screen.width) - 32, 'Continue fills the screen inside its padding');
await browser.close();
console.log('All layer checks passed');
JS
node check-layers.mjsThe order check reads the first @layer statement in the file, the one ending in a semicolon, so a reordered list fails the test even if the page happens to look the same. The width check allows for the screen's 16-pixel padding on each side.
Check it worked
The script prints All layer checks passed. To see a failure, open styles.css, swap vendor and components in the order statement, save and run node check-layers.mjs again: it stops with an AssertionError saying the order does not match. The first assertion fails because the list changed. Comment that assertion out and run again, and the next failure is "components beat vendor: selected day is teal", with the widget's blue rgb(51, 102, 204) as the actual value. Put the order back before you go on.
Step 7 · Clean up
Remove the demo folder, including the Playwright package installed inside it:
cd ~
rm -rf ~/layers-demoPlaywright keeps its browser download in a shared cache (~/.cache/ms-playwright on Linux, ~/Library/Caches/ms-playwright on macOS). Delete that folder too if no other project uses Playwright.
Check it worked
Run ls ~/layers-demo. It reports that there is no such file or directory.
Next steps
- The tokens layer here holds a subset of the Larkfield tokens. Turn design tokens into CSS custom properties builds the full two-layer set and a script that keeps components on the semantic layer.
- Put those tokens on show: build a living style guide page from CSS tokens.
- Tailwind CSS 4 organises its own output in cascade layers. Set up Tailwind CSS 4 with Vite and look for the layer names in the generated CSS.
- Components that change with the space they sit in fit the components layer well: make components responsive with container queries.
Related tutorials
- Make components work in forced colours modeYou will find the Larkfield Clinic components that lose their meaning when Windows forced colours replace the page palette, fix them with a transparent border, currentColor and system colour keywords inside a forced-colors media query, and keep them fixed with a Playwright test that runs under emulation.
- Load web fonts without layout shiftYou will self-host the Larkfield Clinic typeface as one subset WOFF2 file that still covers Yoruba, Hausa, Igbo and Akan letters, preload it, pick a font-display value and tune a fallback font with size-adjust, then measure the page's layout shift falling to near zero.
- Build a living style guide page from CSS tokensYou will have a style guide page that reads every token from tokens.css when it loads and shows the palette with contrast ratios, the type scale, the spacing scale and the Larkfield components in their states, plus a Playwright test that fails when a token is missing.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials