Workbench / Volume 2 Exercises: The Web Frontend
V2·14
CSS
Exercises for Volume 2, chapter 14: selectors, specificity, the cascade, !important, inheritance and cascade layers; values, units and custom properties; the box model, display and formatting contexts, margin collapse, normal flow, flexbox, grid, positioning, containing blocks and stacking contexts; responsive design (mobile-first, fluid type with clamp, media and container queries, responsive media); and modern CSS (nesting, :has(), logical properties, math functions, modern colour spaces and color-mix, scroll-driven animations, view transitions, reduced motion). 10 theory questions, 10 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. CSS problems are best understood by predicting a computed value and then checking it, so nearly every programming exercise asks you to predict what getComputedStyle or getBoundingClientRect will return, then run it in DevTools' Console. The outputs in the solutions come from Chromium 153 in this book's sandbox (a 1,000 px viewport unless stated), and every one was checked by script, including a few that surprise experienced developers (P3, P5, P6).
Use DevTools' Elements panel throughout: the Styles pane shows which rules matched and which were overridden (struck through), Computed shows the final value and where it came from, and the Layout pane overlays flex and grid lines.
Coverage map.
| Chapter component | Exercises |
|---|---|
| selectors, specificity, the cascade, !important, origins | T1, P1 |
| inheritance | T2, P2 |
| cascade layers | T2, P1 |
| values, units, custom properties | T3, P2 |
| box model, box-sizing, margin collapse, formatting contexts | T4, P3 |
| normal flow, display | T4 |
| flexbox | T5, P4 |
| grid | T5, P4 |
| positioning, containing blocks, stacking contexts | T6, P5 |
| responsive design: mobile-first, breakpoints, fluid type, container queries, media | T7, P6, P7 |
| nesting, :has(), logical properties, math functions | T8, P8 |
| colour spaces, color-mix | T9, P9 |
| scroll-driven animations, view transitions, reduced motion | T10, P10 |
Theory
T1. Which rule wins
- Give the order the cascade uses to pick a declaration (origin and importance, layers, specificity, order of appearance, plus inline styles), and compute the specificity of:
#menu .dish,.list li.dish.veg,li:not(#x),ul li,:where(#menu) .dish,:is(#menu, .x) li. - P1 gave one
<li class="dish veg" id="a">all of those rules plus.dish { color: orange !important }early and.dish { color: teal !important }in a later<style>element. The result was teal. Explain. - P1 also showed that
p { color: red !important }beats an inlinestyle="color: blue"but loses to an inlinestyle="color: blue !important". Why, and why is!importantin application CSS usually a sign of a different problem?
T2. Inheritance and layers
- P2 put
color: crimson; border: 3px solid; font-size: 20pxon adiv: the child<p>inherited the colour and font size but not the border; a<button>inside had font size 13.33 px and an<input>black text. Explain which properties inherit, and why form controls didn't. - What do
inherit,initial,unsetandrevertdo? Which would you use in a CSS reset for buttons? - P1 tested
@layer reset, base, components;withbutton.btn#go { background: red }inbase,.btn { background: blue }incomponents, and an unlayered.btn { background: green }: green won. With all three marked!important, thebaseone won. Explain both, and how layers solve the third-party-CSS problem.
T3. Values, units and custom properties
- Compare
px,em,rem,%,vw/vh,dvh/svh/lvh,ch,frandcqi. Which should font sizes, spacing, line lengths and full-height mobile layouts use, and why? - P2 measured
padding-top: 25%on a child of a 400×100 px box as 100 px. What is the percentage relative to, and what old technique used this? - P2's custom properties:
--gap: 16pxon.cardoverrode:root's 8 px for the card but not for a sibling;color: var(--brnd, rgb(1,2,3))(a typo) used the fallback;--w: 20; width: var(--w)pxgave the element its auto width (984 px);--w: 20px; width: calc(var(--w) * 2)gave 40 px. Explain each.
T4. The box model, formatting contexts and margin collapse
- P3 showed an element with
width: 200px; padding: 20px; border: 5pxrendering 250 px wide incontent-boxand 200 px inborder-box(content 150 px). Why isbox-sizing: border-boxthe universal default in resets? - P3: an
<h1>withmargin-top: 40pxinside adivwith a background: the div moved down 40 px from the top and the heading sat at the div's top edge. Withdisplay: flow-rooton the div, the div stayed at 8 px and the heading was 40 px inside it. Explain margin collapse and the fix. - What's a block formatting context, what creates one, and what problems does it solve (floats, margin collapse)? Compare
display: block,inline,inline-block,flex,grid,contentsandnone.
T5. Flexbox and grid
- Explain
flex: 1,flex-grow,flex-shrink,flex-basisand the min-content minimum. P4 put a long unbreakable<pre>line in aflex: 1item of a 300 px row next to a 100 px sidebar: the item grew to 383.5 px (overflowing); withmin-width: 0it stayed at 200 px and scrolled. Why? - P4 also showed a two-column
grid-template-columns: 1fr 1frgrid, 400 px wide, with a long word in one cell: the columns became 504 and 8 px instead of 200 and 200; withminmax(0, 1fr)they were 200 and 200. Explain1frversusminmax(0, 1fr). - When do you use flexbox and when grid? Write the CSS for (a) a header with a logo left and links right; (b) a responsive card grid that fits as many 220 px-minimum cards as possible; (c) a page layout with header, sidebar, main and footer.
T6. Positioning, containing blocks and stacking contexts
- Explain
static,relative,absolute,fixedandsticky, and what the containing block of each is. P5 showed aposition: fixedtoast inside an element withtransform: translateX(0)appearing 200 px down the page (with the element) instead of at the viewport top. Why? - P5: a sticky header inside a container with
overflow: hiddendidn't stick (it scrolled away: −500 px), while without that wrapper it stuck at 0. Explain. - P5: a modal with
z-index: 9999inside a parent withopacity: 0.99was covered by a header withz-index: 1. Explain stacking contexts, list five properties that create one, and how to fix modals and tooltips for good.
T7. Responsive design
- What does "mobile-first" mean in CSS terms, and why is it usually less code than desktop-first?
- P6 measured
font-size: clamp(1.5rem, 1rem + 2.5vw, 3rem)as 24 px at 320 px, 35.2 px at 768 px and 48 px at 1,440 px. Show the arithmetic. Why does fluid type need aremcomponent (accessibility)? - Media queries versus container queries: P7 rendered the same card stacked in a 300 px slot and side by side (
150px 550px) in a 700 px slot with one@container (min-width: 500px)rule. When do you use each? - List the responsive-media techniques (from chapter 13 and this one) that stop images and videos from breaking layouts.
T8. Modern CSS: nesting, :has(), logical properties, math functions
- P8's nested rule
.card { color: blue; & .t { color: red } .x & { color: rgb(1,1,1) } }styled.card .tred and.x .cardnear-black. Explain the&rules, and why deep nesting is still a bad idea. - P8:
.card:has(img)outlined only cards containing an image, andform:has(:invalid) button { opacity: .4 }dimmed the submit button. What can:has()replace that used to need JavaScript, and what are its performance and specificity characteristics? - P8 set
margin-inline-start: 24pxin adir="rtl"block: it becamemargin-right: 24px, whilemargin-left: 24pxstayed on the left. Why do logical properties matter for TiffinBox (Urdu, Arabic, and in general)? - Use
min(),max(),clamp()andcalc()to write: a container that's 1,100 px wide at most and has 16 px gutters on small screens; a sidebar that's 25% wide but never narrower than 200 px; a button whose padding scales with font size.
T9. Colour
- Why are
oklch()andoklab()better thanhsl()for building colour palettes and themes? What does P9'scolor-mix(in oklch, red 50%, blue)(purple at hue 327°) versuscolor-mix(in srgb, …)(color(srgb 0.5 0 0.5), a dull purple) show? - How do you build light and dark themes with custom properties,
prefers-color-scheme,color-schemeandlight-dark()? - What contrast ratios does WCAG require, and why must you check them for every theme, including focus indicators and disabled states?
T10. Motion: transitions, scroll-driven animations, view transitions
- Which properties can be animated cheaply (compositor-only) and which force layout or paint each frame? Why should most UI animation use
transformandopacity(chapter 12's P11)? - What do scroll-driven animations (
animation-timeline: scroll()/view()) and view transitions (document.startViewTransition, cross-document@view-transition) do, and what used to need JavaScript for each? - How do you respect
prefers-reduced-motion, and what counts as motion that must be reducible?
Programming exercises
P1. Cascade puzzles
Predict, then check with getComputedStyle, the colour of <li class="dish veg" id="a"> inside <ul class="list" id="menu"> given: #menu .dish {red}, .list li.dish.veg {blue}, li:not(#x) {green}, .dish {orange !important}, ul li {purple}, and a later <style> with .dish {teal !important}. Then: an important stylesheet rule vs an inline style, with and without !important. Then the cascade-layer cases: @layer reset, base, components with rules in base, components and unlayered, first normal, then all !important.
P2. Inheritance, units and custom properties
Check with getComputedStyle: (a) which of color, border-top-width and font-size a <p> inherits from a styled div, and the font size of a <button> and the colour of an <input> inside it; (b) padding-top: 25% on a child of a 400 × 100 px box; (c) the custom-property cases: an override on .card, a typo with a fallback, var(--w)px, calc(var(--w) * 2), and a sibling reading --gap. Then fix the form-control inheritance with a reset.
P3. Box sizing and margin collapse
Measure (with getBoundingClientRect) a 200 px element with 20 px padding and 5 px border under content-box and border-box; the gap between two paragraphs with margin: 24px 0; and an <h1 style="margin-top: 40px"> inside a background-coloured div, before and after adding display: flow-root (or padding-top: 1px) to the div. Then put the same h1 inside a flex container and measure again.
P4. Flexbox and grid sizing
Measure: (a) a flex: 1 item containing an unbreakable 50-character <pre> line next to a 100 px sidebar in a 300 px row, without and with min-width: 0; (b) a 400 px grid-template-columns: 1fr 1fr grid with a 70-character word in one cell, versus minmax(0, 1fr) with overflow-wrap: anywhere; (c) flex-grow with items of basis 100/100/100 and grow 1/2/0 in a 600 px row. Predict each width first.
P5. Positioning traps
Build three cases and measure: (a) a position: fixed; top: 0 toast inside an element that has transform: translateX(0) and sits 200 px down the page, versus one without the transform; (b) a position: sticky; top: 0 heading inside a scroll container, with and without an intermediate overflow: hidden wrapper, after scrolling 500 px; (c) a z-index: 9999 modal inside a parent with opacity: 0.99, overlapping a sibling header with z-index: 1: which element is at the overlap point (document.elementFromPoint)? Then fix each.
P6. Fluid type with clamp()
Set h1 { font-size: clamp(1.5rem, 1rem + 2.5vw, 3rem) } and measure the computed font size at viewport widths 320, 768 and 1,440 px. Compute the widths at which the size stops growing and starts growing. Then change your browser's default font size to 20 px (Settings → Appearance) and measure again. Finally, design a type scale (body, h3, h2, h1) with clamp() that grows from a 360 px to a 1,280 px viewport.
P7. A component that adapts to its container
Build a dish card that's stacked in narrow slots and has the image beside the text in wide ones, using container-type: inline-size on the slot and @container (min-width: 500px). Place it in a 300 px sidebar and a 700 px main column and read gridTemplateColumns. Then size the card's title with cqi units, and compare with a media-query version placed in the same two slots.
P8. Nesting, :has() and logical properties
Check: (a) the nested .card { & .t {…} .x & {…} } rules; (b) .card:has(img) outlines only the card with an image, and form:has(:invalid) button dims the submit button until a required field is filled; (c) margin-inline-start and margin-left inside dir="rtl". Then replace a JavaScript snippet you've written (toggling a class when a checkbox is checked) with :has().
P9. Colours and themes
Compute color-mix(in srgb, red 50%, blue) and color-mix(in oklch, red 50%, blue) and an oklch(70% 0.15 200) colour, and display them side by side. Then build light and dark themes for a menu card with custom properties and light-dark(), toggle with DevTools' "Emulate prefers-color-scheme" (Rendering panel), and check every text/background pair's contrast with DevTools' colour picker or axe.
P10. Motion that respects users
Build three animations for the menu page: a "sliding cart" panel (animate transform, then the same with left, and compare in DevTools' Performance panel with 6× CPU throttling), a reading-progress bar driven by animation-timeline: scroll(), and a view transition when switching between "Grid" and "List" layouts (document.startViewTransition). Then make all three respect prefers-reduced-motion and test with DevTools' emulation.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–14)
C1. A themeable design-token system
Build TiffinBox's design tokens as CSS custom properties in cascade layers: colour tokens in OKLCH with light and dark themes, a fluid type scale with clamp(), a spacing scale, radii, shadows and a z-index scale; base styles and a reset in their own layers; and components (button, input with label and error, dish card, modal using <dialog>) that use only tokens. Generate the token file from a JSON source with a small Java or Node script, so the same values can be exported to the Android and iOS apps. Check contrast for every text/background token pair automatically (compute WCAG contrast in the script) and fail the build below 4.5:1.
Combines: build scripts and exit codes (Vol 1 ch 01); data transformation (ch 02, 03); number formats and colour maths (ch 06); this volume's HTML semantics (ch 13), accessibility tree (ch 12) and all of this chapter.
C2. The menu page, styled for every screen and language
Style chapter 13's C2 menu page (semantic HTML, 50 dishes) mobile-first: a single column on phones, a card grid with auto-fill and minmax(min(220px, 100%), 1fr) on wider screens, a sticky filter bar that actually sticks (P5), dish cards with container queries (P7), fluid type, logical properties throughout, a dark theme, and reduced motion. Test it at 320, 375, 768, 1,024 and 1,440 px, in an RTL language (add dir="rtl" lang="ur" with sample Urdu text), at 200% zoom and 400% zoom (reflow), with a very long dish name and a 40-character unbroken word, and measure CLS and LCP as in chapter 13's C2.
Combines: Unicode and bidirectional text (Vol 1 ch 06, Volume 23); performance measurement (Vol 1 ch 07, 09); this volume's HTML (ch 13), loading (ch 12) and all of this chapter.
C3. Find and fix CSS regressions automatically
Set up visual regression testing for C2's page: Playwright screenshots of five key states (default, filtered, dark theme, RTL, 320 px) compared against approved baselines with a pixel-difference threshold, plus computed-style assertions for the rules most likely to break (sticky header position after scrolling, no horizontal overflow at 320 px, contrast of key pairs). Then deliberately introduce three regressions (a transform on a wrapper, overflow: hidden on the filter's parent, a removed min-width: 0) and confirm the suite catches each.
Combines: testing and CI exit codes (Vol 1 ch 01, 02); image comparison as array processing (ch 03, 04); thresholds and false positives (ch 05); this chapter's positioning and sizing rules.
What the chapter leaves out
CSS architecture at team scale
How a codebase organises CSS matters more than any single property. Main approaches: naming conventions (BEM: .dish-card__title--featured) with global CSS; CSS Modules (class names scoped per file at build time); utility-first frameworks (Tailwind: compose small classes in markup, with a design-token config); CSS-in-JS (styled-components, Emotion: styles defined in components, often with run-time cost, losing favour for zero-run-time variants like vanilla-extract and Panda); and native scoping (@scope, shadow DOM in web components). Whatever the choice: tokens in custom properties, cascade layers for ordering, low and predictable specificity, co-locating component styles with components, and a lint setup (Stylelint) to enforce it.
Fonts and text rendering
Web fonts affect performance and layout: each weight and style is a file (use variable fonts and subset to needed scripts: Latin, Devanagari, Telugu ranges with unicode-range); font-display: swap shows fallback text immediately, but the swap can shift layout unless the fallback is adjusted with size-adjust, ascent-override and similar descriptors (frameworks like Next.js generate these); preload the one or two fonts used above the fold. Indic scripts need fonts with proper shaping support (conjuncts, matras) and more generous line-height; test real text, not lorem ipsum. Volume 23's typography chapter covers script-specific issues.
Forced colours, high contrast and user styles
Windows High Contrast / forced colors mode replaces your colours with the user's palette: backgrounds and borders defined only by colour may vanish, background images carrying information disappear, and custom focus indicators drawn with box-shadow are removed. Test with @media (forced-colors: active) emulation in DevTools; use real borders/outlines (transparent ones become visible), currentColor for SVG icons, and system colour keywords (CanvasText, Highlight, ButtonText) where needed. Similarly, respect user font sizes (rem) and prefers-contrast.
Rendering performance of CSS
Selectors are rarely the bottleneck, but some CSS is expensive: huge DOMs with complex layouts, box-shadow/filter on many large elements, animating layout properties (T10), and forced synchronous layout from scripts (chapter 12's T8). Tools: content-visibility: auto with contain-intrinsic-size lets the browser skip rendering off-screen sections (big wins on long menus); contain: layout paint isolates components; will-change promotes layers but costs memory (use sparingly, temporarily). Measure in DevTools' Performance panel (Recalculate Style, Layout, Paint timings) before optimising; chapter 27 covers the rest.
Anchor positioning and the popover API
Tooltips, dropdowns and menus used to need JavaScript libraries (Popper, Floating UI) to position them next to their trigger and keep them on screen. Newer CSS and HTML features cover most of it: the popover attribute (top layer, light dismiss, no z-index issues: T6) and CSS anchor positioning (anchor-name, position-anchor, position-area, position-try-fallbacks to flip when there's no room), supported in Chromium and arriving elsewhere. Combined, they give accessible-by-default dropdowns with far less code; check current browser support (chapter 12's gaps) and keep a fallback.
Senior exercises
S1. Diagnose "the checkout button is hidden on some phones"
Users on some Android phones report that the "Place order" button at the bottom of the checkout is hidden behind the browser's toolbar, and on iPhones a fixed bottom bar jumps when scrolling. The page uses height: 100vh on the layout and position: fixed; bottom: 0 for the bar. Explain the causes (viewport units, dynamic toolbars, safe areas, the virtual keyboard), how to reproduce them, and the fix.
S2. Set the CSS conventions for a growing team
Three teams contribute to TiffinBox's web app; the stylesheet has 400 !importants, 60 ID selectors, and z-indexes up to 2147483647. Write a migration plan to a maintainable architecture (layers, tokens, component scoping, specificity rules, z-index scale), with enforcement (Stylelint rules), a measurable target, and how to do it incrementally without a big-bang rewrite.
S3. Review a CSS pull request
A PR adds a promotional banner: .promo { position: fixed; top: 0; width: 100vw; height: 80px; z-index: 99999; font-size: 14px; color: #999; background: url(banner.jpg); animation: slide 0.5s infinite alternate; }, plus .header { margin-top: 80px !important; } and * { transition: all 0.3s; }. Write the review, ranked by severity.
S4. Decide on a styling approach for a new frontend
TiffinBox is starting a new React app (chapter 22) and the team debates Tailwind, CSS Modules, and a CSS-in-JS library. Compare them on run-time cost, server rendering, theming with tokens, design-system sharing with non-React apps, developer experience, onboarding, bundle size, and long-term maintenance. Recommend one with justification and conditions.
S5. Teach the "why did my layout break?" debugging method
Write a one-page debugging guide for engineers new to CSS: a step-by-step method using DevTools to diagnose any layout or styling bug, with the five most common causes from this chapter and the quick check for each.