Workbench / Volume 2 Companion: The Web Frontend
V2·14
CSS
Companion to Volume 2, chapter 14: how the cascade, layout and responsive CSS connect; new angles (the cascade as a knockout tournament, specificity as version numbers, layout as a negotiation, design tokens as a price list); what the chapter simplifies, measured in Chromium: nested light and dark panels where the outer theme wins, the `hidden` attribute losing to `display: flex`, `line-height: 1.5em` squashing headings, a valid earlier declaration that doesn't rescue an invalid `var()`, and focus rings that vanish in forced-colours mode; the theory behind it; how a specificity calculator is written (and two selectors it scores wrongly); four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 14 has three strands. The cascade: selectors pick elements, specificity scores them, the cascade (origin, layers, order) picks one winning declaration per property, inheritance fills the gaps, and values (units, custom properties) are resolved. Layout: the box model, formatting contexts and normal flow, then flexbox and grid for arranging children, positioning against containing blocks, and stacking contexts for painting order. Responsive and modern CSS: media and container queries, fluid type, nesting and :has(), colour and motion.
The links worth remembering:
- Specificity only decides within a layer and origin. It's the fourth question the cascade asks, not the first. A long selector in an earlier layer loses to a single class in a later one, which is what makes layers a tool for taming specificity wars.
- Inheritance is the cascade's only sense of nearness. Selectors don't know which ancestor is closer (Gaps 1); inherited values do, because each element takes its parent's value. Custom properties inherit, so design tokens get "closest wins" for free.
- Layout is decided by parents, sized by children. Flex and grid containers decide how space is shared; the items' content decides how small they can get (min-content) and how big they want to be (max-content). Most "why won't this shrink?" bugs are an item's content refusing what its container offered.
Explain it differently
1. The cascade is a knockout tournament with fixed rounds. Every declaration for a property on an element enters. Round 1: origin and importance (user-agent, user, author; !important reverses the order). Round 2: context (shadow DOM). Round 3: style attribute. Round 4: layers. Round 5: specificity. Round 6: scope proximity (for @scope rules). Round 7: order of appearance. A declaration knocked out in round 4 never reaches round 5, however specific it is. Most cascade confusion is people judging a match by round 5 when it was decided in round 4.
2. Specificity is compared like version numbers. (1, 0, 0) beats (0, 15, 0) for the same reason version 1.0.0 is newer than 0.15.0: the columns are compared left to right, and a column never "carries" into the next. Eleven classes don't make an ID. It's a sort key, not a score.
3. Inheritance hands down the result, not the recipe. A child inherits its parent's computed value. If the parent's line-height is 1.5em, that's computed as 24 px (for a 16 px font), and the child inherits 24 px, whatever its own font size. A unitless 1.5 is inherited as the number 1.5 and multiplied by each element's own font size (Gaps 3). Pass down the recipe when descendants differ.
4. Layout is a negotiation between parent and child. The parent says "here's the space I have" (constraints go down); the child says "I can't be narrower than my longest word, and I'd like to be as wide as my text on one line" (intrinsic sizes go up). Flexbox and grid are rules for settling that negotiation among many children at once. A long URL that won't shrink is a child that never agreed to the deal (min-width: auto).
5. Flexbox splits leftover space like a restaurant bill. First everyone orders (each item's flex-basis). Then the total is compared with the table's budget (the container). Money left over is shared by flex-grow shares; an overspend is clawed back by flex-shrink weighted by each item's basis, so big orders give back more. Nobody gives back below their minimum (min-content), which is why some bills don't balance (overflow).
6. Grid is a planned layout; flexbox is a queue. A grid lays out the streets first (tracks) and then places buildings into plots; items align across rows and columns because the plan says so. Flexbox lets each item take its place in a queue and sizes the line around them. Use grid when the layout comes first, flexbox when the content comes first.
7. Design tokens are a restaurant's price list. The menu (components) refers to names: --surface, --text, --accent. A theme is a new price list: change the list and every dish's price changes, without reprinting the menu. Dark mode, high contrast and a kitchen's own brand colours are all just different price lists, scoped to the part of the page they apply to (Gaps 1).
8. Custom properties are template placeholders filled in late. The browser can't check color: var(--brand) when it parses the stylesheet, because it doesn't know yet what --brand will hold on each element. It fills the placeholder at computed-value time, and if the result is nonsense, it's too late to fall back to an earlier declaration (Gaps 4). Parse-time errors are forgiven; computed-time errors are quietly reset.
Gaps and misconceptions
What the chapter oversimplifies
All measurements below are real, from Chromium 153 through Playwright, reading getComputedStyle.
1. "Within @scope, the closer scope root wins": and without it, the nearer ancestor doesn't. The chapter lists scope proximity as a cascade step. What it doesn't show is the bug it exists to fix: nested themes. A light panel inside a dark page, and a dark panel inside a light page, styled three ways:
/* themes */ .light p { color: rgb(20,20,20) } .dark p { color: rgb(240,240,240) }
/* scope */ @scope (.light) { p { color: rgb(20,20,20) } } @scope (.dark) { p { color: rgb(240,240,240) } }
/* tokens */ .light { --text: rgb(20,20,20) } .dark { --text: rgb(240,240,240) } p { color: var(--text) }
themes a (light inside dark): rgb(240, 240, 240) | b (dark inside light): rgb(240, 240, 240)
scope a (light inside dark): rgb(20, 20, 20) | b (dark inside light): rgb(240, 240, 240)
tokens a (light inside dark): rgb(20, 20, 20) | b (dark inside light): rgb(240, 240, 240)
With plain selectors, .light p and .dark p both match the paragraph inside both panels, with equal specificity, so the later rule wins everywhere: near-white text on a white panel. Descendant selectors know that an ancestor exists, not which ancestor is nearer. @scope adds proximity to the cascade; custom properties get it from inheritance, which is proximity by construction (each element takes its nearest ancestor's value). That's the strongest argument for theming with tokens: nested themes simply work (drill D1).
2. "hidden hides an element": unless any CSS sets its display. The hidden attribute works through one rule in the browser's own stylesheet, [hidden] { display: none }. The user-agent origin loses to every author rule, so:
hidden: .filters [True, 'flex', 22] | plain div [True, 'none', 0]
The filter bar has hidden set (the DOM says true) and is still 22 px tall on screen, because .filters { display: flex } won the cascade (drill D2). Most CSS resets add [hidden] { display: none !important } for this reason; author !important beats author normal rules.
3. "line-height is inherited": as a computed length, when it has a unit. Two wrappers with 16 px text, one with line-height: 1.5em and one with 1.5, each containing a 32 px heading that wraps to two lines:
line-height a ['32px', '24px', 48, '2 lines']
line-height b ['32px', '48px', 96, '2 lines']
The em version computed 24 px on the wrapper, and the heading inherited 24 px: two lines of 32 px text in 48 px of height, overlapping. The unitless version inherited the factor and computed 48 px for the heading (Explain it differently 3). Unitless line-height is the default for anything with descendants (drill D3).
4. "Invalid declarations are ignored": at parse time. At computed-value time, they reset the property. Each paragraph below has color: blue followed by a second declaration; the body is green:
#a { color: blue; color: 20px } /* invalid when parsed */
#b { color: blue; color: var(--brand) } /* --brand: 12px */
#c { color: blue; color: var(--brnad) } /* typo: undefined, no fallback */
#d { margin-left: 10px; margin-left: var(--brand-colour, red) }
iacvt a ['rgb(0, 0, 255)', '0px']
iacvt b ['rgb(0, 128, 0)', '0px']
iacvt c ['rgb(0, 128, 0)', '0px']
iacvt d ['rgb(0, 128, 0)', '0px']
#a's bad declaration was thrown away when parsed, so color: blue won: the familiar forgiving CSS. But #b, #c and #d are only found to be invalid when the variable is substituted, after the cascade has already picked the var() declaration as the winner. The earlier color: blue is gone; the property becomes unset: inherited for color (green, from the body), the initial value for margin-left (0, not 10 px). This is why the "write a fallback declaration first" pattern from the pre-variables era doesn't protect var(); use the var(--x, fallback) argument, @property with a syntax and initial-value, or @supports (Chapter Exercises P2 shows the var(--w)px case; this is the rule underneath it).
5. Forced colours: the user's palette replaces yours, and box-shadow focus rings disappear. Chapter Exercises names this in what the chapter leaves out. Measured with Playwright's forced_colors="active" (the emulation of Windows contrast themes), a button with border: 0, a green background and a focus ring drawn as box-shadow: 0 0 0 3px #fa0:
forced-colors none | focused box-shadow ring: ['rgb(255, 170, 0) 0px 0px 0px 3px', 'none', 'rgb(255, 255, 255)', 'rgb(0, 187, 102)'] | focused transparent-outline fix: ['rgb(255, 170, 0) 0px 0px 0px 3px', 'solid', 'rgba(0, 0, 0, 0)'] | chip: ['rgb(0, 187, 102)', 'rgb(255, 255, 255)']
forced-colors active | focused box-shadow ring: ['none', 'none', 'rgba(5, 0, 73, 0.8)', 'rgb(255, 255, 255)'] | focused transparent-outline fix: ['none', 'solid', 'rgba(5, 0, 73, 0.8)'] | chip: ['rgb(255, 255, 255)', 'rgb(0, 0, 0)']
(The first list is the button's box-shadow, outline style, outline colour and background; the second the same for a button that also has a transparent outline; the third the chip's background and text colour.)
In forced colours, box-shadow is forced to none, backgrounds become the system's, and the "Veg" chip that was green is just text. The focused button has no visible focus indicator at all, and with border: 0 it doesn't look like a button either: in the screenshot, "Place order" is plain text. The fix costs nothing in normal mode: outline: 3px solid transparent (invisible normally, recoloured with a system colour in forced mode) and border: 2px solid transparent (likewise). With both, the screenshot shows two bordered buttons and a clear focus outline (drill D4).
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "The nearer ancestor's rule wins." | Selectors ignore distance; only @scope and inheritance know nearness. |
Gaps 1; drill D1 |
"The hidden attribute always hides." |
It's a user-agent display: none, beaten by any author display. |
Gaps 2; drill D2 |
"1.5em and 1.5 are the same line height." |
Same on the element; different for every descendant with another font size. | Gaps 3; drill D3 |
| "Invalid CSS is ignored, so an earlier declaration still applies." | Only parse-time errors. A var() that turns out invalid makes the property unset. |
Gaps 4 |
"outline: none is fine if I add a box-shadow ring." |
Forced-colours mode removes box-shadows; use a transparent outline. | Gaps 5; drill D4 |
| "Higher specificity always wins." | Only after origin, importance, context and layers have tied. | Explain it differently 1 |
| "Eleven classes beat an ID." | Specificity columns never carry over. | Explain it differently 2 |
Theoretical gaps: the ideas behind the chapter
1. The cascade is a sort with a total order. For one property on one element, the browser collects every matching declaration and sorts by a composite key: (origin and importance, context, style attribute, layer, specificity, scope proximity, order of appearance). The first wins. Thinking of it as ORDER BY with seven columns explains every cascade puzzle, and why the key's order is a design decision: putting layers before specificity is what lets a team write simple selectors in a later layer and beat complex ones in an earlier layer.
2. Error handling chose forward compatibility. CSS parsers drop declarations and rules they don't understand and carry on. That's what lets a stylesheet use a feature old browsers don't know (the declaration is ignored there, and an earlier fallback applies) and why @supports can exist. Custom properties broke that model: the parser can't know whether var(--x) will be valid, so it accepts it, and errors surface later, at computed-value time, where the only safe recovery is to reset the property (Gaps 4). @property restores parse-time typing for registered variables.
3. Layout is a two-pass constraint problem. Intrinsic sizes flow up the tree (how small and how big content can be), and available space flows down (how much room the container gives). Flex and grid algorithms are specified ways to resolve conflicts between the two. It's why layout costs grow with the depth of dependencies, and why "size depends on content, which depends on size" cases (percentages of indefinite heights, auto tracks) have special rules.
4. Proximity is the missing dimension of selectors. Selectors describe structure ("a p somewhere inside .dark"), not distance. For three decades, nearness came only from inheritance, which is why theming with inherited custom properties beat theming with selectors (Gaps 1). @scope adds proximity to the cascade explicitly, between specificity and order of appearance in the sort key: equally specific rules are settled by the nearer scope root before the later rule gets a say.
5. User preferences are part of the cascade by design. CSS has always had a user origin: the reader can override the author. Forced colours, user font sizes, zoom, reduced motion and dark mode are modern forms of that principle. Accessible CSS is CSS that leaves room for the user's choices (relative units, real outlines and borders, motion as an enhancement) instead of fighting them.
6. Perceptual colour is not RGB. Equal steps in RGB aren't equal steps to the eye, which is why lightening by mixing with white muddies colours and why palettes built in HSL have uneven contrast. OKLCH separates perceived lightness, chroma and hue, so a theme can set lightness for contrast and keep the hue. Contrast itself has two models: WCAG 2's ratio (the legal standard today) and APCA, a perceptual model proposed for future guidelines, which weighs text size and polarity (dark-on-light against light-on-dark) differently. Know which one an audit uses.
Applying it
Code walkthrough
How is specificity actually computed? specificity 1.0.0 (the library behind the Specificity Calculator website) parses a selector with css-tree and walks the tree. Excerpts from dist/esm/calculate.js, installed from npm.
Walking the selector tree
var traverse = function (node, accumulatingResult) {
if (accumulatingResult === void 0) { accumulatingResult = {
total: { A: 0, B: 0, C: 0 },
contributingParts: [],
}; }
if (node.type === "IdSelector") {
return increment(node, accumulatingResult, "A");
}
else if (node.type === "PseudoClassSelector") {
return handlePseudoClassSelector(node, accumulatingResult);
}
else if (node.type === "ClassSelector" ||
node.type === "AttributeSelector") {
return increment(node, accumulatingResult, "B");
}
else if (node.type === "TypeSelector") {
if (node.name !== universalSelectorName) {
return increment(node, accumulatingResult, "C");
}
}
else if (node.type === "PseudoElementSelector") {
return increment(node, accumulatingResult, "C");
}
else if (node.type === "Selector" || node.type === "SelectorList") {
return node.children.reduce(function (acc, childNode) { return traverse(childNode, acc); }, accumulatingResult);
}
...
The three columns are named A, B and C, as in the Selectors specification. IDs add to A; classes, attributes and pseudo-classes to B; types and pseudo-elements to C; * and combinators add nothing (combinators aren't even mentioned: they fall through to return accumulatingResult). The result is immutable: increment returns a new object with one column bumped and the contributing part's position recorded (for the website's highlighting).
The functional pseudo-classes
if (name === "not" || name === "is" || name === "has") {
// The specificity of an :is(), :not(), or :has() pseudo-class is replaced by the specificity of the most specific complex selector in its selector list argument
if (children.length > 0) {
return children
.map(function (childNode) { return traverse(childNode, accumulatingResult); })
.sort(function (a, b) { return compareDesc(a.total, b.total); })[0];
}
}
else if (name === "nth-child" || name === "nth-last-child") {
// ... the pseudo class itself (counting as one pseudo-class selector) plus the specificity of the most specific complex selector in its selector list argument (if any).
...
}
else if (name === "where") {
// The specificity of a :where() pseudo-class is replaced by zero.
return accumulatingResult;
}
Each comment quotes the specification, and the code is a direct translation: :is(), :not() and :has() try each argument on top of what's been counted so far and keep the largest (sorted with the same left-to-right comparison as Explain it differently 2); :where() adds nothing; :nth-child(… of S) adds one pseudo-class plus the largest argument. Everything else (:hover, :focus-visible) is one B. And sort.js's comparison is the version-number rule exactly:
export var compare = function (a, b) {
if (a.A !== b.A) { return a.A - b.A; }
else if (a.B !== b.B) { return a.B - b.B; }
else { return a.C - b.C; }
};
Real results (node t.mjs):
ul#nav li.active a:hover (1,2,3)
:where(#main) .card (0,1,0)
:is(#main, .x) p (1,0,1)
:not(.a, #b) (1,0,0)
li:nth-child(2n of .veg) (0,2,1)
.card:has(> img) (0,1,1)
p::before (0,0,2)
p:before (0,0,2)
* (0,0,0)
Note p:before (one colon): the parser sees a pseudo-class, and the code checks a list of four legacy pseudo-elements to count it in C instead of B. It's history encoded as a special case, like the form encoder's character sets in the Companion to chapter 13.
Read it yourself
- What does the library return for
:host(.dark)and::slotted(.price)(used inside web components' shadow styles), and is it right? - What happens if you pass
.a, #b?
Debugging drills
D1. White text on a white card
The kitchen dashboard is dark-themed. A new "today's specials" panel inside it is meant to be light, using the existing .light theme class. The panel's text is near-white on white. The theme CSS:
.light p, .light li { color: rgb(20,20,20) }
.dark p, .dark li { color: rgb(240,240,240) }
Explain, and fix it so themes can nest to any depth.
D2. The filters won't hide
The menu page has a "Filters" toggle. The script sets filters.hidden = !filters.hidden. In the DOM, the attribute toggles correctly, and DevTools shows hidden on the element, but the filter bar stays on screen. It worked before a CSS refactor.
D3. Overlapping headings in the dish cards
Dish names in cards overlap themselves when they wrap to two lines: the second line sits on top of the first. Body text is fine. The card CSS:
.card { font-size: 1rem; line-height: 1.5em; }
.card h3 { font-size: 2rem; }
D4. "I can't see where I am" in high contrast
A customer using Windows' contrast theme reports that on the checkout page, she can't tell which button has keyboard focus, and the "Place order" button "looks like plain text". In normal mode, buttons are green with an orange focus ring. The CSS:
button { border: 0; background: #0b6; color: #fff; }
button:focus { outline: none; box-shadow: 0 0 0 3px #fa0; }
Career-oriented
Interview prep
Mid level
Q1. What are the ways to hide something in CSS and HTML, and when would you use each?
How to get there. List the options, then compare them on three questions: is it still laid out (takes space)? Is it still in the accessibility tree (read by screen readers)? Can it receive focus? Then give a use for each.
Q2. Two developers argue: one wants !important to fix a style that won't apply, the other says never use it. What do you do?
How to get there. Diagnose before fixing: find out why the rule loses (DevTools' Styles pane shows the winning declaration and crossed-out losers). Then discuss what !important does to the cascade's order, and where it's legitimately used.
Senior level
Q3. TiffinBox launches in Telugu, Hindi and Urdu. What changes in the CSS?
How to get there. Think about scripts (glyph heights, shaping), direction (Urdu is right-to-left), fonts (size and fallback), and text length. Name concrete CSS properties for each. Chapter Exercises P8 covers logical properties; go beyond them.
Q4. Scrolling the menu page on mid-range Android phones is janky, and the team suspects CSS. How do you investigate and what do you look for?
How to get there. Chapter Exercises leaves rendering performance out. Measure first (Performance panel with CPU throttling or a real device), identify which rendering phase is expensive (style, layout, paint, composite), then match to typical CSS causes.
Staff level
Q5. Set the policy for when TiffinBox's teams may use new CSS features (container queries, :has(), @scope, anchor positioning).
How to get there. A policy needs a data source (which browsers customers use), a definition of "supported", a rule for features that are almost supported, and a way to enforce it. Think about who owns the decision and how it changes over time.
Q6. An established server-rendered app with 15 years of global CSS, and a new React frontend being built beside it. How do you get one visual language across both without a rewrite?
How to get there. Find what can be shared without sharing implementation: tokens. Then decide how each codebase consumes them, how conflicts between old and new CSS are prevented, and how the migration progresses.