Skip to content
Tech Interview Prep
Technical interview guideNew

CSS Fundamentals and Layout

How the box model, cascade, flexbox, grid, positioning, responsive design, and units decide what a browser actually renders, and how to debug when they don't.

Read
15 min
Practice MCQs
25
Interview Q&A
25
Edition
v1
Editorial status
Reviewed
Relevant for
Frontend Engineer

Scope: CSS Living Standard, current to 2025. Baseline browser support as of Chrome 131, Firefox 133, Safari 18 (late 2024/early 2025)..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the CSS box model and how width and height are computed under content-box versus border-box.

Answer

The 90-second answer. The box model is four nested rectangles: content, padding, border, margin. width and height name one of them, and box-sizing decides which. Under the initial value content-box, width sizes the content box only, so padding and border are added on top of it. Under border-box, width sizes the border box (content, padding and border together) and the content box is whatever is left. Margin sits outside both: box-sizing never counts it, so width: 100% plus any margin still overflows the parent.

content-box (initial)border-box
width applies tocontent boxborder box
rendered border-box widthwidth + padding + borderwidth
content widthwidthmax(0, width − padding − border)

Worked, with width: 300px; padding: 0 20px; border: 2px solid:

  • content-box: content 300px, padding 40px, border 4px → 344px rendered.
  • border-box: 300px rendered, content box 300 − 40 − 4 = 256px.
/* checked in Chrome 126, Firefox 127, Safari 17 */
*, *::before, *::after { box-sizing: border-box; }

box-sizing is not an inherited property, so the * selector is doing the work. The html { box-sizing: border-box } *, *::before, *::after { box-sizing: inherit } variant exists so one subtree can opt back out with box-sizing: content-box.

Why most codebases flip the default. Percentage widths, padding and grid tracks then compose without arithmetic. The failure it prevents: a width: 50% card with padding: 16px under content-box is 50% + 32px wide, so two of them plus a gap overflow the row and you get a horizontal scrollbar at some viewport widths but not others.

What border-box does not change. Percentage widths still resolve against the containing block's content box, not the element's own box. Percentage padding, including padding-top and padding-bottom, resolves against the containing block's inline size, which is why a 16:9 box is written padding-top: 56.25%. And border-box cannot shrink below padding plus border: width: 10px; padding: 20px renders 40px wide with a zero-width content box.

Failure modes, and how you catch each.

  1. Overflow from content-box arithmetic. Detect: document.documentElement.scrollWidth > document.documentElement.clientWidth, or DevTools' overflow badge on the container.
  2. Flex or grid items that refuse to shrink. min-width: auto floors a flex item at its content size regardless of box-sizing; min-width: 0 is the fix. Detect: the item's getBoundingClientRect().width exceeds the track size.
  3. Reading the wrong measurement in JS. getBoundingClientRect() and offsetWidth are border-box; clientWidth is the padding box (content + padding, no border, no scrollbar); scrollWidth includes overflow. A layout calculation that mixes them is off by the border width: 4px here, which is exactly the kind of bug that only shows at one zoom level.

When not to use border-box. Rarely. It is the wrong tool when padding should grow the element rather than eat into a fixed content area, a button whose label must occupy a fixed 200px content width, but min-width plus content-box on that one element expresses that more honestly.

Curated: · Written: · Reviewed:

Q&A-12

Walk me through px, em, rem, %, vw/vh, dvh and ch: what each resolves against, and the production bug each one causes.

Answer

The 90-second answer. A CSS length is a number plus a unit, and the unit only means something relative to a context. Name the context and you can predict the bug.

  • px is a CSS pixel (an abstract unit, nominally 1/96in) anchored to nothing the user controls except zoom.
  • em resolves against the element's own computed font-size; when you're setting font-size itself, it resolves against the parent's.
  • rem resolves against the root element's font-size.
  • % resolves against the containing block for width/height, the parent's font-size for font-size, and, the trap, the containing block's width for all four sides of padding and margin.
  • vw/vh are 1% of the viewport width/height.
  • dvh is 1% of the current viewport height, which changes as mobile browser chrome shows and hides.
  • ch is the advance width of the "0" glyph in the current font.
UnitResolves againstBug it causesFix
pxnothing user-controlledignores the user's default font-size preference; WCAG 1.4.4 failsrem for type
emown or parent font-sizecompounds: 0.8em inside 0.8em is 0.64emrem, or em only for spacing that should track its own text
remroot font-sizehtml { font-size: 10px } overrides the user's preferencehtml { font-size: 62.5% }, or leave it at 100%
%containing blockvertical padding/margin resolve against widthaspect-ratio, or padding-block
vw/vhviewport100vh on mobile extends behind the URL bar; 100vw includes the scrollbardvh/svh, or 100%
dvhcurrent viewportchanges during scroll, so it re-lays-outsvh for stable chrome, dvh for a hero
ch"0" glyph widtha font swap changes it and shifts layoutfont-display: optional, or measure after document.fonts.ready

The em compounding trace. Root font-size 16px:

.parent { font-size: 0.8em; } /* 12.8px */
.child  { font-size: 0.8em; } /* 10.24px — not 12.8px */
.grand  { font-size: 0.8em; } /* 8.192px */

Three levels of "80%" is 51% of the original. rem breaks the chain: each of those is 12.8px, because they all resolve against the root.

The line-height inheritance bug. line-height: 1.5 is inherited as the number, so each element multiplies its own font-size. line-height: 24px or 1.5em is inherited as the computed value, so a child with font-size: 32px still gets 24px of leading and the lines collide. Use the unitless number.

The 100vh arithmetic. Take a phone whose viewport is 393×852 CSS px with the URL bar hidden and 393×745 with it shown. height: 100vh resolves to 852px, so a full-height hero puts 107px of content behind the browser chrome. 100dvh resolves to 745px when the bar is shown and 852px when it is hidden: correct, but it re-lays-out on every scroll, so don't put it on a container with expensive descendants. 100svh is always 745px: stable, and the right choice for a sticky footer. dvh, svh and lvh shipped in Safari 15.4, Chrome 108 and Firefox 101.

Failure modes, and how you catch each.

  1. Type that won't scale. body { font-size: 16px } means a user whose browser default is 24px still sees 16px. Detect: change the browser's default font size in settings and reload; the page should scale.
  2. Percentage padding that isn't square. padding-top: 100% on a 300×200 box gives 300px of top padding, not 200px. Detect: resize the container's width only and watch the "square" change shape.
  3. ch after a font swap. max-width: 65ch is measured against the fallback font, then the webfont loads with a wider "0" and the measure changes. Detect: Lighthouse CLS, or measure after document.fonts.ready.

Curated: · Written: · Reviewed:

Q&A-4

Explain the difference between inheritance, the cascade and specificity, and when you'd reach for inherit, initial, unset or revert?

Answer

The 90-second answer. Three mechanisms, routinely conflated, and the interview is mostly about keeping them apart. The cascade is the algorithm that picks one winning declaration for a property on an element. It sorts by origin and importance first (UA < user < author, and !important reverses that), then cascade layers, then specificity, then order of appearance. Specificity is only a tiebreaker inside one origin and one layer: it never beats !important, and it never beats a later layer. Inheritance is not in that contest at all. If no declaration wins, an inherited property takes the parent's computed value and a non-inherited one takes its initial value. color inherits; margin does not, and no amount of specificity on the parent makes it inherit.

The four keywords are all about which value you fall back to:

keywordresolves towhere it earns its place
inheritparent's computed value, even for non-inherited propertiesfont: inherit on <button>/<input>, border: inherit on a nested element
initialthe property's initial value from the spec, ignoring the UA stylesheetalmost never; display: initial on a <div> is inline
unsetinherit if the property is inherited, initial otherwiseall: unset to strip a subtree
revertthe value from the previous origin: for author CSS, the UA stylesheetdisplay: revert on a <button> keeps inline-block
/* checked against Chrome 126, Firefox 127, Safari 17 */
button { all: unset; }   /* display:inline, padding:0, border:none — the UA look is gone */
button { all: revert; }  /* back to the UA stylesheet's button */

revert-layer is the same idea one level down: it rolls back to the previous @layer rather than the previous origin.

Specificity arithmetic, and the two functions that break intuition.

#nav .item a:hover { }   /* (1,2,1) — 1 id, 2 classes/pseudo-classes, 1 type */
:where(#nav) .item a { } /* (0,1,1) — :where() contributes zero, always */
:is(#nav, .list) a { }   /* (1,0,1) — :is() takes the highest of its arguments */

:where() is the tool for a reset or a design-system base rule that must never win a fight. :is() is the one that surprises people, because adding a selector to its argument list can raise the whole rule's specificity.

Failure modes.

  1. color: initial is not black. The initial value of color is CanvasText, a system color that follows the user's theme, so it renders light in dark mode. If you want the UA default that is revert; if you want the parent's, that is inherit.
  2. all: unset on a form control or a heading deletes UA styles you were relying on: an <h1> becomes inline-sized text with no margins. Detect it by diffing computed styles before and after, not by eyeballing.
  3. !important from a component library that consumers can only beat with their own !important. The fix is @layer: for normal declarations unlayered styles beat layered ones, and for !important declarations the layer order reverses, so the override goes in a layer declared before the library's, also !important.
  4. Custom properties inherit by default, and --x: initial makes the variable guaranteed-invalid, so var(--x, fallback) silently takes the fallback. That is the usual cause of "my token is empty" bugs.

Curated: · Written: · Reviewed:

Q&A-3

How is specificity calculated, and how do !important, inline styles and cascade layers interact with it?

Answer

The 90-second answer. Specificity is a three-part tuple, not a number: (IDs, classes/attributes/pseudo-classes, types/pseudo-elements). Compare left to right: #a at (1,0,0) beats .b.c.d.e.f.g.h.i.j.k at (0,10,0). *, combinators and :where() contribute nothing; :is(), :not() and :has() take the specificity of their most specific argument.

Specificity is only the fifth tiebreaker. The cascade sorts by: origin and importance → shadow context → element-attached (inline) styles → cascade layers → specificity → order of appearance. So !important, inline styles and layers all outrank specificity, which is why "just write a more specific selector" stops working the moment one of them is in play.

@layer reset, components;   /* order fixed here: reset loses to components */

@layer reset      { a { color: black; } }      /* 0-0-1, layer 1 */
@layer components { .nav a { color: blue; } }  /* 0-1-1, layer 2 */
a { color: green; }                            /* 0-0-1, unlayered */

<a class="nav"> renders green. Unlayered normal declarations beat every layered normal declaration regardless of specificity. Delete the unlayered rule and it is blue: the later layer wins and specificity is never consulted.

Now add !important to all three. It renders black: importance reverses layer order (the first layer wins) and layered important beats unlayered important. That is the point of putting !important in a reset layer: it becomes a floor nothing in your design system can override except inline.

Inline styles sit in their own step before layers. <a class="nav" style="color: purple"> is purple, beating all normal author declarations. style="color: purple !important" is still purple, beating all important author declarations including layered ones. Only important user-agent or user declarations (forced-colors mode) and transitions outrank it.

DeclarationBeats
normal inlineall normal author
normal unlayeredall normal layered
normal later layernormal earlier layer
important earlier layerimportant later layer
important layeredimportant unlayered
important inlineall important author
transitioneverything

Failure modes, and how you catch each.

  1. A vendor stylesheet imported unlayered beats your layered design system. DevTools' Styles pane shows the vendor rule winning with no layer name next to it. Fix: @import url(vendor.css) layer(vendor);.
  2. !important arms race. Count !important per file; if a rule needs two of them to win, the cascade is already lost. The fix is :where() to zero out a reset's specificity, not another !important.
  3. JS-set inline styles. el.style.display = 'none' silently beats the stylesheet, and toggling classes will not remove it. Check element.style.cssText in the console.
  4. :where() in a reset has zero specificity by design. If you expected it to hold against a component rule, it will not: that is the feature, not the bug.

When not to reach for these: revert-layer drops a declaration back to the previous layer's value, which is usually what you actually wanted when you were about to write !important.

Curated: · Written: · Reviewed:

Q&A-18

Walk me through CSS custom properties: how scoping and inheritance work, what a var() fallback actually covers, and how you'd wire up a runtime theme switch.

Answer

The 90-second answer. A custom property is a declaration whose name starts with -- and whose value is an arbitrary token stream. Two things separate it from a Sass variable: it lives in the cascade, and it inherits. Declare --brand on :root and every element can read it; declare it on .promo and only .promo and its descendants see that value. var(--brand) substitutes the token stream at computed-value time, so the consuming property resolves per element, not per stylesheet.

That gives you theming with one write: tokens on :root, the same names overridden under [data-theme="dark"], one attribute flipped on <html>.

:root { --brand:#0b5fff; --surface:#fff; --text:#111; --space:8px; }
[data-theme="dark"] { --surface:#111; --text:#f5f5f5; }

.promo { --brand:#b8003c; }   /* re-scopes for this subtree only */

.card {
  background: var(--surface);
  color: var(--text);
  border-inline-start: 4px solid var(--brand, #999);
  padding: calc(var(--space) * 2);
}
document.documentElement.dataset.theme = 'dark';  // one write, whole tree recomputes

Scoping is inheritance, not specificity. .promo's --brand wins inside .promo because it is the nearest ancestor that sets it, not because .promo outranks :root. A rule that matches .card itself would beat both, by ordinary cascade rules. Names are case-sensitive: --Brand and --brand are two different properties.

What the fallback covers. var(--x, #999) uses #999 only when --x is guaranteed-invalid: never declared, or declared as initial. It does not cover a value that is set but wrong for the property. Everything after the first comma is the fallback, so var(--pad, 4px 8px) is fine and var(--a, var(--b, red)) nests.

The trap is what happens next. A declaration containing var() is assumed valid at parse time and only checked after substitution. If the substituted value doesn't fit the property, the declaration is invalid at computed-value time and the property becomes unset: inherited if it's an inherited property, initial if it isn't. It does not fall back to the previous declaration in the cascade:

.card { color: red; color: var(--typo); }  /* not red — color inherits from the parent */

That is why a typo'd name is silent: either the fallback fires, or the property quietly goes unset, and nothing errors.

Registration changes the rules. @property gives a custom property a type, an initial value and an inheritance flag.

@property --brand { syntax: '<color>'; inherits: true; initial-value: #0b5fff; }
unregistered --x@property with syntax: '<color>'
Value checkedno, any token streamyes, at computed-value time
var(--x, fb) fallback fireswhen never setnever: initial-value applies
transition: --x .3sdiscrete, flips at 50%interpolates
Inheritsalwaysinherits: false allowed

Support: Chrome/Edge 85 (2020), Safari 16.4 (2023), Firefox 128 (2024).

Failure modes.

  1. Flash of the wrong theme. The attribute is set by a script that runs after first paint. Fix: a small blocking inline script in <head> that reads localStorage and prefers-color-scheme and sets document.documentElement.dataset.theme before the body renders. Detect: throttle to Slow 3G and watch the first frame.
  2. var() in a media query. @media (min-width: var(--bp)) is invalid: media and container query conditions don't accept var(). Detect: the rule silently never matches; the Styles pane shows the at-rule with no effect.
  3. Empty value is not a missing value. --x: ; is valid and empty, so var(--x, red) substitutes nothing and the property goes unset rather than red. Detect: the Computed pane shows the inherited value, not the fallback.
  4. A token leaking into a subtree. A component that sets --surface for its own purposes changes every descendant that reads --surface. Detect: the Computed pane shows the value arriving from an unexpected ancestor. Fix: namespace the token (--card-surface) or register it with inherits: false.

When not to use them. Custom properties resolve per element at computed-value time, so they can't be read by media queries or @supports conditions, and a deep inherited token tree is harder to trace than a build-time variable. For values that never change at runtime, a Sass variable is cheaper.

Curated: · Written: · Reviewed:

Q&A-10

Walk me through how you'd make a page responsive: mobile-first versus desktop-first, how you choose breakpoints, and what the viewport meta tag is doing.

Answer

The 90-second answer. Ask what the layout must do at the narrowest width you support, then decide which direction the cascade accumulates. Mobile-first: the base stylesheet is the small-screen layout and every media query is min-width, adding complexity as room appears. Desktop-first: the base is the wide layout and every query is max-width, stripping things away. Same pixels either way. The difference is that in mobile-first the unqualified rules are the ones a phone gets, so a missing or unsupported media query degrades to the simplest layout rather than the most complex one.

The viewport meta is not optional. Without it a mobile browser lays out against a fallback width, 980px in Chrome and Safari on iOS, and scales the result down, so every min-width query fires as though the screen were a desktop.

<meta name="viewport" content="width=device-width, initial-scale=1">

width=device-width sets the layout viewport to the device's CSS pixel width; initial-scale=1 sets the starting zoom. Adding maximum-scale=1 or user-scalable=no blocks pinch-zoom, which fails WCAG 1.4.4, and iOS has ignored user-scalable=no since iOS 10 anyway.

/* mobile-first: base is small, min-width adds */
.card { display: grid; gap: 1rem; grid-template-columns: 1fr; }

@media (width >= 48em) { .card { grid-template-columns: repeat(2, 1fr); } }
@media (width >= 64em) { .card { grid-template-columns: repeat(3, 1fr); } }

/* desktop-first: base is wide, max-width removes */
.card { grid-template-columns: repeat(3, 1fr); }
@media (width < 64em) { .card { grid-template-columns: repeat(2, 1fr); } }
@media (width < 48em) { .card { grid-template-columns: 1fr; } }

width >= 48em is Media Queries Level 4 range syntax (Chrome 104, Safari 16.4, Firefox 102); the older (min-width: 48em) is identical and still fine.

Breakpoints. Pick them where the content breaks, not where devices are. A workable default set: 48em (768px) for two columns, 64em (1024px) for three, 80em (1280px) for a sidebar. Note that em inside a media query resolves against the initial font size, 16px unless the user changed it, not against html { font-size }. So 48em is 768px for most users and 960px for a user at 20px, which is the point: em breakpoints respect the user's font-size preference, px breakpoints don't.

Failure modes.

  1. Horizontal overflow. A fixed width: 320px child plus padding inside a 320px viewport. Detect with document.documentElement.scrollWidth > document.documentElement.clientWidth, or the DevTools overflow badge.
  2. 100vw includes the scrollbar. On desktop Chrome/Windows the scrollbar is ~15px, so a width: 100vw element is 15px wider than its parent and produces a horizontal scrollbar. Use 100%.
  3. 100vh on mobile. It resolves to the large viewport, URL bar hidden, so a full-height hero is taller than the screen while the bar is showing. Use 100dvh (Chrome 108, Safari 15.4, Firefox 101) or svh.
  4. Hover-only affordances. A dropdown opened on :hover is unreachable on touch. Gate it behind @media (hover: hover).
  5. Breakpoints that only exist in one direction. A max-width: 767px query and a min-width: 768px query leave a 1px gap at fractional zoom; range syntax avoids it.

When not to. If a component appears in both a narrow sidebar and a wide main column, viewport queries can't express it. Container queries (@container (width >= 30rem), Chrome 105, Safari 16, Firefox 110) make the component respond to its container instead. And for type and spacing that should scale smoothly, clamp(1rem, 2.5vw, 2rem) removes a breakpoint rather than adding one.

Curated: · Written: · Reviewed:

Q&A-11

When would you reach for a container query over a media query, and what does browser support look like today?

Answer

The 90-second answer. A media query asks about the viewport. A container query asks about the nearest ancestor that has been declared a containment context. If a card has to look right in a 320px sidebar, a 700px modal, and a full-width page, a media query cannot know which of those it is in: it only sees the viewport. A container query lets the card respond to the space it was actually given, which is what makes a component genuinely reusable.

/* Declare the containment context on the parent */
.card-slot {
  container-type: inline-size;
  container-name: card;
}

/* Query it from the component */
@container card (min-width: 30rem) {
  .card { grid-template-columns: 8rem 1fr; }
}

Mechanism. container-type: inline-size applies contain: layout inline-size style to the element. The inline size (width, in horizontal writing modes) is now resolved independently of the element's contents. That independence is the whole trick: without it, a query on the container's width would be circular. The width depends on the children, the children's layout depends on the query, the query depends on the width. Containment breaks the cycle, so the browser can answer the query before laying out the children.

container-type: size adds block-size containment too, so the element's height also ignores its contents. That is why a size container with no explicit height collapses to zero: a common first bug.

When each. Media queries for anything that depends on the device or the page: prefers-color-scheme, prefers-reduced-motion, print styles, and page-level layout such as a nav rail versus a bottom bar. Container queries for reusable components whose layout depends on the slot they land in: cards, media objects, data tables, form rows. They compose: a media query picks the page shell, container queries inside it adapt the components.

Failure modes.

  1. Query never matches. No ancestor has container-type. Detect: the rule is greyed out in DevTools; check computed container-type up the tree.
  2. container-type: size collapses the box. No intrinsic height. Detect: zero-height element in the layout inspector.
  3. Intrinsic sizing surprises. With inline-size containment, the container's width no longer depends on its children, so width: max-content on the container gives the max-content of the container, not of the content. Detect: unexpected shrink inside a flex row.
  4. Style queries assumed to have parity. @container style(--x: y) shipped later than size queries and is not interchangeable.

Support. Container size queries are Baseline since February 2023: Chrome/Edge 105, Safari 16, Firefox 110. Style queries shipped later (Chrome 111, Safari 18, Firefox 128) and are Baseline Newly available as of late 2024. Check caniuse for the exact target before relying on style queries. For a target older than size-query support, gate the container-query version behind @supports (container-type: inline-size) and keep a media-query fallback that approximates the same breakpoints.

Curated: · Written: · Reviewed:

Q&A-5

Walk me through how flex-grow, flex-shrink and flex-basis resolve an item's size, and why a flex item with long content overflows its container instead of shrinking.

Answer

The 90-second answer. Flexbox lays items out along one axis. flex-direction picks the main axis (row is horizontal, column is vertical), and the cross axis runs perpendicular to it. justify-content distributes space on the main axis and align-items on the cross axis. Each item's main size is resolved in three steps. First, flex-basis sets the starting size (auto falls back to width or height, then to content). Second, the free space is the container's main size minus the sum of the bases. Third, positive free space is shared out by flex-grow and negative free space is taken back by flex-shrink. The shorthands are flex: 1 = 1 1 0%, flex: auto = 1 1 auto, and flex: none = 0 0 auto.

The overflow comes from the automatic minimum. For a flex item, min-width: auto (and min-height: auto in a column container) resolves to the content-based minimum, which is the longest unbreakable word or the widest unbreakable child. Shrinking cannot take an item below that floor, so a row with long content overflows even when the shrink factors say it should fit.

Grow and shrink with numbers. Container 600px wide.

itemflexbasisfree spacefinal
A1 1 00600 × 1/3200px
B2 1 00600 × 2/3400px
A′1 1 auto, content 100px100px300 × 1/2250px
B′1 1 auto, content 200px200px300 × 1/2350px

A basis of 0 makes the grow factors the only input, which is why flex: 1 gives equal columns whatever their content. A basis of auto adds the content size first, so the same grow factor gives unequal columns.

Shrinking is weighted by basis as well as by factor. Take three items at flex: 1 1 300px in a 600px container. Free space is 600 − 900 = −300px. Each item's scaled shrink factor is 1 × 300 = 300, the total is 900, and each item gives back 300 × (300/900) = 100px, so each ends at 200px.

The overflow, concretely. Assume a 400px card, and a button whose content is 80px wide (a hypothetical figure for this trace).

/* Chrome 120, Firefox 121 */
.card  { display: flex; width: 400px; }
.title { flex: 1 1 0; white-space: nowrap; }
<div class="card">
  <span class="title">[900px of unbroken text]</span>
  <button>Save</button>
</div>

Trace it the way the algorithm runs. .title has basis 0, so its hypothetical size is 0. Its automatic minimum is its min-content width, 900px, and the clamp raises it to 900px. The button's basis is its content, 80px, and its minimum is also 80px. The row is 980px inside a 400px card, so the card overflows by 580px. Adding min-width: 0 to .title removes the floor. Free space becomes 400 − 0 − 80 = 320px, .title grows to 320px, and the button stays at 80px. The text is still 900px wide, so it spills out of the item unless the item clips it.

For truncation, use overflow: hidden on .title together with text-overflow: ellipsis. Any overflow value other than visible also computes the automatic minimum to 0, so the item shrinks to 320px and the ellipsis appears. You do not need min-width: 0 as well. Nested flex containers need the floor removed at each level where the content would otherwise set the size.

Failure modes and how to detect them. A horizontal page scrollbar, or content clipped where you expected truncation, usually means the item's computed min-width is auto and its used width equals its min-content width. Check this in DevTools and toggle min-width: 0 in the inspector. flex-shrink: 0 also prevents shrinking by design, so rule it out before blaming the automatic minimum. In a column container the same bug shows up as vertical overflow through min-height: auto.

Flexbox is one-dimensional. When rows and columns need to line up with each other, use grid.

Curated: · Written: · Reviewed:

Q&A-2

A child with width: 100% and horizontal padding overflows its flex parent. Walk me through how you diagnose it.

Answer

The 90-second answer. Two mechanisms stack here, and you have to separate them before you touch anything. box-sizing defaults to content-box, so width: 100% sizes the content box and padding and border are added outside it: the item's outer width is 100% + padding-left + padding-right + border-left + border-right. And because the parent is a flex container, whether that excess is visible depends on whether flex-shrink can absorb it, which it cannot do below the item's automatic minimum size, min-width: auto.

So: measure the item's outer width against the container's content box, then ask why the shrink didn't happen. Those are two different bugs with two different fixes.

Worked trace. Container content box 600px, display: flex. Child: width: 100%; padding: 0 16px; border: 1px solid.

  • flex-basis: auto resolves to width, so the flex base size is 600px (content box).
  • Hypothetical outer size = 600 + 32 + 2 = 634px. Free space = −34px.
  • One item, flex-shrink: 1, scaled shrink factor 600 → it absorbs all 34px. Content box 566px, outer 600px. No overflow.

Same markup, but the item's min-content width is 580px: a long unbreakable token, white-space: nowrap, a nested flex row, an image, a <pre>:

  • The automatic minimum size floors the item at 580px content width.
  • Outer = 580 + 34 = 614px → 14px of overflow.

Or flex-shrink: 0 on the item: outer stays 634px → 34px of overflow. Same symptom, different cause.

/* reproduces 34px of overflow at a 600px container */
.row  { display: flex; width: 600px; }
.cell { width: 100%; padding: 0 16px; border: 1px solid; flex-shrink: 0; }

Fixes, and what each one actually changes.

FixWhat it changes
box-sizing: border-box (global)width: 100% now includes padding and border; outer = 600px
min-width: 0 on the itemremoves the automatic minimum size floor
flex: 1 1 0 + width: autobase size 0, grows to fill; no percentage to overflow
overflow-wrap: anywherelowers min-content for long strings

Setting overflow to anything other than visible on the flex item also zeroes the automatic minimum size: that is why overflow: hidden "fixes" it, and why it is the wrong fix: it clips content the user cannot reach. overflow-x: hidden on the container is worse, because it hides the symptom for every child.

Detecting it. In DevTools the flex overlay draws the item's outer size against the container's content box, and the computed min-width on the item shows the used value rather than auto. el.getBoundingClientRect().width against container.clientWidth gives you the number in one line. Grid items have the same min-width: auto behaviour, so the identical bug shows up in grid-template-columns: 1fr 1fr.

One more trap: percentage padding resolves against the containing block's inline size, so padding: 0 5% adds 10% of the container's width, not 10% of the item's.

Curated: · Written: · Reviewed:

Q&A-6

Walk me through CSS Grid: how the explicit and implicit grids differ, what an fr unit actually resolves against, and when you'd reach for auto-fit over auto-fill.

Answer

The 90-second answer. Grid is two grids. The explicit one is what you declare with grid-template-columns and grid-template-rows. Anything placed outside it (an item past the last declared row, or grid-column: 5 against a three-column template) lands in the implicit grid, whose tracks are sized by grid-auto-rows / grid-auto-columns, both defaulting to auto. That default is the first thing to check when rows come out uneven.

fr is not a percentage. It is a share of the free space left after gaps and non-flexible tracks are subtracted. In a 1000px container with a 200px fixed column and 20px gaps, 1fr 2fr gets free = 1000 − 200 − 40 = 760, so 253.33px and 506.67px. A percentage would have resolved against the container and ignored the gaps, which is how 33.33% 33.33% 33.33% plus gaps overflows.

The trap is that 1fr is shorthand for minmax(auto, 1fr), and that auto minimum is a min-content floor. A long unbreakable token or a wide <pre> in a 1fr track pushes the track past its share and the whole grid overflows. minmax(0, 1fr) removes the floor.

/* Chrome 126, Firefox 127 */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-auto-rows: minmax(120px, auto); /* implicit rows, not the default auto */
  gap: 20px;
}

auto-fit and auto-fill differ only when there are fewer items than tracks. Both create as many tracks as fit. auto-fill keeps the empty ones, so items sit at their minimum and the row ends in empty space. auto-fit collapses the empty tracks to zero and the remaining 1fr tracks absorb that space, so items stretch.

Worked on a 1000px container, 20px gap, repeat(auto-*, minmax(200px, 1fr)), three items:

tracks createditem width
auto-fill4 (one empty, still 235px)235px
auto-fit4, one collapsed to 0320px

Four tracks is the most that fit: 4×200 + 3×20 = 860 ≤ 1000. auto-fill splits the remaining 140px across all four tracks, 35px each. auto-fit drops the empty track and splits 1000 − 40 = 960 across three.

Failure modes.

  1. Grid overflow from the 1fr floor. Detect with container.scrollWidth > container.clientWidth, or the DevTools grid overlay showing a track wider than its share. Fix: minmax(0, 1fr), or min-width: 0 on the item.
  2. Uneven implicit rows. grid-auto-rows defaults to auto, so each implicit row is content-sized and one three-line title makes its whole row taller. Fix: grid-auto-rows: 1fr or minmax(120px, auto).
  3. auto-fit with a single item. It stretches across the viewport, which reads as broken for a card grid. Use auto-fill when the track size must hold.
  4. repeat(auto-fit, …) in an indefinite-width container, inside width: max-content or a shrink-to-fit context, resolves to one track, because the track count depends on a definite inline size.

Reach for Flexbox when the layout is one-dimensional and the items size themselves; Grid when two axes have to line up. grid-auto-flow: dense backfills holes left by items spanning columns, at the cost of visual order diverging from DOM order.

Curated: · Written: · Reviewed:

Q&A-13

Walk me through min-content, max-content and fit-content, and what changes when you use them as grid track sizes or as flex bases?

Answer

The 90-second answer. The three keywords are one formula. min-content is the narrowest the box can get before its content overflows: for text, the widest unbreakable unit, usually the longest word. max-content is the width if nothing ever wrapped. fit-content(<limit>) is the clamp between them: min(max-content, max(min-content, limit)). The bare fit-content keyword is that same clamp with the available space as the limit, so it shrink-wraps but never exceeds its container. They are not only width values: they are grid track sizes, and they are what the auto minimums in grid and flex resolve to.

A 500px container holding one sentence whose longest word is 130px and whose unwrapped line is 640px (16px system font, illustrative figures: measure your own):

declarationused widthwhy
width: min-content130pxlongest word
width: max-content640pxone line; overflows the 500px container
width: fit-content500pxmin(640, max(130, 500))
width: fit-content(300px)300pxmin(640, max(130, 300))

In grid. Track sizes take the same keywords, and auto as a track size is minmax(auto, max-content): it grows to fit content, then absorbs free space.

.panel {
  display: grid;
  grid-template-columns: max-content minmax(0, 1fr);
  gap: 8px;
}

max-content sizes the label column to the longest label; the value column takes the rest. The minmax(0, 1fr) is the load-bearing part: 1fr is shorthand for minmax(auto, 1fr), and auto as a minimum is the item's automatic minimum size. Its min-content contribution. A long unbreakable token in the value column (a URL, a commit hash) therefore floors the track above the container width and the grid overflows. minmax(0, 1fr) removes the floor; pair it with overflow-wrap: anywhere so the text can actually break.

In flex. flex-basis accepts the same keywords, and flex items carry the same automatic minimum.

.row { display: flex; gap: 8px; }
.row > .label { flex: 0 0 max-content; }
.row > .value { flex: 1 1 0; min-width: 0; }

flex-basis: max-content with flex-shrink: 0 pins the label at its longest line. The value item needs min-width: 0 for the grid reason: its min-width is auto, which resolves to the content-based minimum, so it refuses to shrink below its longest word. Setting overflow to anything other than visible also zeroes that automatic minimum, which is why overflow: hidden on a flex child appears to fix the overflow while silently clipping content.

Failure modes, and how you catch each.

  1. A 1fr track wider than its container. Detect: the track's used size exceeds the container's content box. The DevTools grid overlay shows the track crossing the container edge. Fix: minmax(0, 1fr).
  2. A flex child that won't shrink. Detect: the item's used width equals its min-content width and the row overflows. Fix: min-width: 0 plus overflow-wrap: anywhere, not overflow: hidden.
  3. width: max-content on a block inside a page. The block ignores its container and the document scrolls sideways. Detect: document.documentElement.scrollWidth > document.documentElement.clientWidth. Fix: fit-content or max-width: 100%.
  4. An image setting the floor. min-content on a container holding a 1200px image is 1200px, so the track never shrinks. Detect: the track's minimum equals the image's intrinsic width. Fix: max-width: 100% on the image.

When not to use them. Intrinsic keywords make a box's size depend on its content and on the font that actually loaded, so they are a poor fit for columns that must align across rows: use fixed tracks or subgrid there. They are also not animatable; animate between lengths instead.

Curated: · Written: · Reviewed:

Q&A-7

When would you reach for flexbox versus grid for a given UI, say a card row versus a page layout?

Answer

The 90-second answer. Ask two questions: is the layout one-dimensional or two-dimensional, and does the content decide the size or does the layout? Flexbox is a one-dimensional layout model: it distributes space along a single axis (row or column) and sizes items based on their content and flex factors. Grid is two-dimensional: you define rows and columns, and items are placed into that structure. So a card row, a nav bar, a toolbar, a form field with a label and input: flexbox. A page layout with header, sidebar, main, footer, or a dashboard with overlapping panels: grid. If you find yourself nesting flex containers to fake a two-dimensional alignment, that's the signal to switch to grid.

Mechanism and trade-offs. Flexbox's main axis is set by flex-direction; items grow, shrink, and wrap along that axis. The container's size is often driven by its content, unless you constrain it. Grid's tracks are defined first (grid-template-columns, grid-template-rows), and items are placed into cells or areas. Grid can overlap items, and grid-template-areas makes the layout readable. Flexbox has no concept of rows and columns simultaneously; flex-wrap creates lines but you cannot align items across lines. Grid can do that with align-items and justify-items on the grid container.

Here's a quick comparison:

FlexboxGrid
Dimensions1D (row or column)2D (rows and columns)
SizingContent-driven, flex factorsLayout-driven, track sizing
PlacementOrder in source, order propertyExplicit lines, areas, auto-placement
AlignmentAlong main and cross axisBoth axes, per track
Use caseCard row, nav, toolbarPage layout, dashboard, overlapping

Code. A card row with flexbox:

.card-row {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}
.card {
  flex: 1 1 250px; /* grow, shrink, basis */
}

A page layout with grid:

.page {
  display: grid;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  gap: 1rem;
  min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

Trace. Suppose a flex container is 600px wide with gap: 20px and three items each flex: 1 1 0. The gaps take 40px, leaving 560px. Each item gets 560 / 3 ≈ 186.67px. If one item has flex: 2 1 0, it gets 2/4 of 560 = 280px, the others 140px each. With grid, grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) on an 800px container with 20px gap: available width after gaps is 800 - 40 = 760px. 760 / 250 = 3.04, so 3 columns fit, each 760 / 3 ≈ 253.33px. That's a responsive card grid without media queries.

Failure modes. Using flexbox for a two-dimensional layout leads to nested flex containers and alignment that breaks when content changes. Using grid for a simple row of items can be overkill and makes content-driven sizing harder: you have to use auto tracks and minmax(). Also, flexbox's flex-basis: auto means items size to content, which can cause overflow if content is wider than the container; min-width: 0 on flex items is often needed to allow shrinking. Grid items have min-width: auto by default too, so minmax(0, 1fr) is a common fix.

When to combine. Use grid for the page skeleton and flexbox inside components. That's the common pattern: grid places the major regions, flexbox arranges items within a region.

Curated: · Written: · Reviewed:

Q&A-14

Walk me through how you'd debug a layout bug in devtools: the box model diagram, the Styles versus Computed panes, and the grid and flex overlays. What does each one tell you that the others don't?

Answer

Assumptions: Chrome DevTools, current stable. Other browsers have equivalent panels under different names.

Start at the symptom element only long enough to confirm it. Then walk up the tree until the box model stops matching what the CSS should produce. Each surface answers a different question, so read them in this order.

1. Box model (bottom of the Computed pane). It shows the used numbers for content, padding, border and margin, and hovering a number highlights that region on the page. If the content box is right but the total is wrong, suspect padding, border or box-sizing. If the content box is wrong, the cause is upstream: a track size, a percentage resolved against a parent, or a min or max constraint.

2. Computed. One resolved value per property, with a link to the rule that won. Use it to answer what value is in effect right now. It is not the used value. min-width: auto on a grid or flex item typically reads auto there, while the used minimum is the item's content-based minimum. You have to work that out yourself.

3. Styles. Every matched rule in cascade order, with losing declarations struck through. It includes the user-agent stylesheet and :where() rules at zero specificity. Use it to answer which declaration set a value and what it beat. If a Computed value has no visible source here, check the UA stylesheet (h2 gets margin-block of 0.83em by default) or a reset you forgot you loaded.

An un-struck declaration is not necessarily in effect. It can win the cascade and still do nothing, because the property does not apply to that element.

4. Layout overlays. The Layout pane lists the grid and flex containers on the page. Ticking one draws its lines. Grid overlays show resolved track sizes, so you can see the real track count that repeat(auto-fit, minmax(240px, 1fr)) produced. Flex overlays show each item's basis, grow and shrink. The grid outline follows the content box, so padding appears as an inset from the border.

Worked case. Two columns, grid-template-columns: 240px 1fr, and the article refuses to sit in column 2.

<div class="grid">
  <aside>...</aside>
  <div class="wrapper"><article class="main">...</article></div>
</div>
.grid { display: grid; grid-template-columns: 240px 1fr; gap: 24px; }
.main { grid-column: 2; }

Select .main. The box model is fine. Styles shows grid-column: 2 un-struck. Computed shows grid-column-start: 2. The Layout pane lists one grid container, and its item in track 2 is .wrapper, not .main. The parent of .main is a plain block, so grid-column applies to nothing. Fix: remove the wrapper, or give it display: contents.

Console checks (after selecting the element in Elements):

$0;                                          // selected element
getComputedStyle($0).width;                  // resolved value, not authored
$0.getBoundingClientRect();                  // border box, viewport-relative, fractional
$0.offsetWidth;                              // border box, integer, layout-rounded
getComputedStyle($0.parentElement).display;  // if not grid, grid-column is inert

Failure modes.

  • Debugging the symptom element instead of walking up until the box model stops matching.
  • Reading an un-struck declaration as in effect.
  • Treating Computed as the used value.
  • Concluding the page has no grid because the Layout pane is empty. More likely, your display: grid lost the cascade or sits on the wrong element.
  • Fixing it with live edits in Styles and calling it done. Those edits are lost on reload. A production build with a different @layer order, or a minifier that drops a rule, can cascade differently, so confirm the fix in the built output.

Curated: · Written: · Reviewed:

Q&A-8

Walk me through how position: absolute, fixed and sticky each pick their containing block, and the layout failure each one causes when you get it wrong.

Answer

The 90-second answer. position answers two questions at once: does the element stay in normal flow, and which rectangle do top/right/bottom/left resolve against? That rectangle is the containing block, and it is not the same ancestor for every value.

valuein flow?containing block for offsetsoffsets measured from
staticyesn/a: offsets ignored—
relativeyes, space reservedits own normal-flow positionits own box
absolutenonearest ancestor with position != static; else the initial containing blockthat ancestor's padding box
fixednothe viewport (initial containing block)viewport
stickyyesnearest block container ancestor (same as static)nearest scrollport

Two rules people miss. First, absolute resolves against the padding box of the positioned ancestor, not the content box, so a parent with padding: 24px and no position set does not contain the child at all; the child escapes to the initial containing block. Second, relative with no offsets is still useful: it makes the element a containing block for absolute descendants and, with z-index other than auto, a stacking context. That is the standard "position: relative wrapper" idiom.

The fixed-position trap. fixed is documented as viewport-relative, but any ancestor with transform, filter, perspective, backdrop-filter, will-change: transform, or contain: paint|layout becomes the containing block instead. This is how a modal ends up clipped inside a card:

css /* Chrome 124, no vendor prefixes / .card { transform: translateZ(0); } / added for GPU compositing / .overlay { position: fixed; inset: 0; } / now positioned to .card, not the viewport */

Detect it in DevTools: select the fixed element and the containing-block highlight is the card, not the viewport. The fix is to move the overlay out of the transformed subtree (portal it to body) or drop the transform.

Sticky's two conditions. sticky stays in flow and behaves like relative until a scroll threshold is crossed, then like fixed, but only inside its containing block. It needs (a) a non-auto offset such as top: 0, and (b) a scrollport. If any ancestor has overflow: hidden, auto, or scroll, that ancestor becomes the scrollport; if it never scrolls, the element never sticks. This is the most common "sticky doesn't work" report:

html

<div style="overflow: hidden"> <!-- becomes the scrollport --> <header style="position: sticky; top: 0">…</header> </div>

The header sticks to a box with no scroll range, so it looks static. Detect by walking ancestors in DevTools for a computed overflow that is not visible.

Failure modes.

  1. Absolute child escapes to the viewport because no ancestor is positioned: detect via the containing-block highlight in DevTools.
  2. Fixed element scrolls with a transformed ancestor: detect by toggling the ancestor's transform in the Styles pane and watching the overlay jump.
  3. Sticky never activates because of an overflow ancestor or a missing offset: detect by checking computed overflow up the tree and confirming top is set.
  4. z-index on a static element is ignored: detect by checking computed position; only positioned elements (and flex/grid items) participate.

When not to use them. Prefer normal flow plus flex/grid for layout; reach for absolute for overlays anchored to a known box, fixed for chrome that must survive scrolling, and sticky for headers inside a scroll container. relative with offsets is usually a smell: it moves paint without moving layout, so siblings overlap.

Curated: · Written: · Reviewed:

Q&A-9

A dropdown with z-index: 9999 still paints underneath a sibling card with z-index: 1. Explain why, and how you'd fix it without just raising the number.

Answer

The 90-second answer. z-index is not a global dial. It is resolved inside the nearest ancestor that forms a stacking context, and a descendant's z-index can never lift it above a sibling of that ancestor. z-index: 9999 means "top of my parent's stack", not "top of the page". Two things break it in practice: z-index is ignored entirely on position: static elements, and an ancestor can become a stacking context without anyone writing z-index on it. opacity, transform, filter, will-change and isolation all do it.

Here is the failure, reproduced in Chrome 126:

<style>
  .toolbar { position: relative; opacity: 0.99; } /* leftover from a fade-in */
  .menu    { position: absolute; z-index: 9999; }
  .card    { position: relative; z-index: 1; }
</style>
<div class="toolbar"><div class="menu">Export…</div></div>
<div class="card">Billing</div>

.toolbar has opacity: 0.99, so it forms a stacking context with an effective z-index: auto: painted as z-index: 0 in the root context. .card has z-index: 1. The root context therefore paints the entire toolbar subtree first, then the card. Inside the toolbar's context the menu is on top of its siblings, which is worth nothing: the whole context sits below the card. Raise .toolbar to z-index: 2 and the menu reappears: proof that the number was never the problem.

Paint order inside one stacking context (CSS 2.1 Appendix E, simplified): background and borders of the context-forming element → negative-z-index children → in-flow non-positioned blocks → floats → inline content → z-index: 0/auto positioned descendants → positive-z-index children. Every level is atomic: nothing inside a child context interleaves with anything outside it.

What creates a stacking context: worth memorising, because most of these are invisible in the CSS you're reading:

TriggerTypical accidental source
position + z-index ≠ autothe intended case
position: fixed or stickyany z-index, even auto
opacity < 1opacity: .99 after a fade animation
transform, filter, perspective, backdrop-filter, clip-path, mask ≠ nonetransform: translateZ(0) GPU hack
will-change naming any of the abovecreates it before the change happens
isolation: isolatethe deliberate one
contain: layout/paint/strict/contentperf work elsewhere in the app
flex or grid item with z-index ≠ autono position needed
mix-blend-mode ≠ normal

Fixes, in the order I'd try them. (1) Find the capping ancestor and give it the z-index: correct, but it couples two components that shouldn't know about each other. (2) Move the overlay out of the subtree: render it into document.body or, better, use the top layer. <dialog>.showModal() and the popover attribute paint above every stacking context and escape overflow: hidden clipping, which no z-index can do. (3) Put isolation: isolate on component roots so internal z-index values are scoped and can never leak into the page's stack.

Detection. Chrome DevTools flags stacking-context creators in the Elements panel; when a z-index looks inert, I check the ancestor chain's computed opacity, transform, filter and will-change before touching the number. The failure mode to name out loud: a fade-in animation that leaves opacity: 0.99 behind, silently capping every tooltip in that component for the next two years.

Curated: · Written: · Reviewed:

Q&A-15

A child's margin-top is pushing its parent down instead of creating space inside it. Walk me through why that happens and how you'd debug it.

Answer

The 90-second answer. In normal flow, adjacent vertical margins between block-level boxes collapse: instead of adding, they combine into one margin equal to the largest of them, plus the most negative one if any are negative. Horizontal margins never collapse, and neither do margins in flex or grid containers. Three cases: adjacent siblings, a parent and its first or last child, and an element's own top and bottom margins when it's empty. The nested case is the one that breaks layouts, because a child's margin-top escapes the parent and moves the parent instead of creating space inside it.

The condition for parent/child collapsing: nothing separates the parent's top border edge from the child's top margin. No border, no padding, no inline content, no clearance, and the parent doesn't establish a block formatting context.

Worked trace.

html

<div class="a">A</div> <div class="parent"><div class="child">child</div></div>

css .a { margin-bottom: 10px; } .parent { margin-top: 0; background: #eee; } .child { margin-top: 30px; }

What you'd expect: 10px between A and parent, 30px of grey above the child. What you get: 30px between A and parent, max(10, 30), and the child flush against the parent's top edge, with no grey above it. The child's margin didn't disappear; it moved outside the parent and merged with the parent's own top margin.

Empty block: <div style="margin: 20px 0"></div> between two siblings contributes 20px, not 40px, because its own top and bottom margins are adjacent.

Negative margins: the collapsed value is the largest positive plus the most negative. 20px against -10px gives 10px; -20px against -10px gives -20px.

Debugging it. DevTools' box-model panel shows the margin rendered outside the parent's border box: that's the tell. Then check the conditions in order: is there a border, padding, inline content or clearance between the two margins? Is the parent a block formatting context? If no to both, it's collapsing.

Fixes.

FixEffectCost
display: flow-root on the parentCreates a BFC, stops parent/child collapsingNone; purpose-built
padding-top or border-top on the parentSeparates the marginsChanges the parent's box size
overflow: hidden on the parentCreates a BFCClips overflow; breaks position: sticky descendants
display: flex / grid on the parent, spacing via gapNo collapsing at allChanges the children's layout algorithm
padding on the child instead of marginNo margin to collapsePadding is inside the box, so it affects background and sizing

display: flow-root is the one to reach for: it establishes a BFC with no other side effects, and it's supported in every current browser (Chrome 58+, Firefox 53+, Safari 13+).

Failure modes. The one that ships: a card component with margin-top on its heading, dropped into a page where the card has no padding. The heading's margin pushes the whole card down and the page looks like it has a stray gap. Detect it by inspecting the card in DevTools and seeing the margin drawn outside its border box. The second: a design system that spaces stacked components with margins, where the real gap is max() of two margins rather than their sum, so spacing is inconsistent depending on which components end up adjacent. That's the argument for gap in flex/grid containers, where spacing is explicit and never collapses.

Curated: · Written: · Reviewed:

Q&A-16

Walk me through the overflow property: what each value does, when an element becomes a scroll container, and the bugs that follow from getting it wrong?

Answer

The 90-second answer. overflow decides what happens to content that does not fit an element's padding box. Five values: visible (the default. Content spills), hidden (clipped), clip (clipped, and unlike hidden it does not create a scroll container), scroll and auto (clipped and scrollable). The distinction that matters in production is not clipping, it is that everything except visible and clip turns the element into a scroll container, and a scroll container changes how descendants position and how wheel events propagate.

valueclipsscroll containerscrollable by script/focusscrollbar space
visiblenonononone
clipyesnononone
hiddenyesyesyesnone shown
scrollyesyesyesalways reserved
autoyesyesyesonly when overflowing

Two rules fall out of that table.

Axes are paired. If one axis is visible and the other is neither visible nor clip, the visible one computes to auto. So overflow-x: hidden; overflow-y: visible actually gives you overflow-y: auto. You cannot clip one axis and let the other spill.

The root propagates. overflow on html is applied to the viewport. If html is visible, the body's value is used instead and body itself computes to visible. That is why body { overflow: hidden } locks page scroll in one app and does nothing in another.

Failure modes, and how you catch each.

  1. A sticky header that never sticks. Sticky is constrained to its nearest scrollport. An ancestor with overflow: hidden is a scrollport that never scrolls, so the header has nowhere to travel.
.panel        { overflow: hidden; }        /* scroll container, but nothing scrolls */
.panel__head  { position: sticky; top: 0; } /* pinned to a box that never moves */

Detect: DevTools shows a scroll badge on the ancestor and computed overflow-y: hidden. Fix: drop the overflow, or move the scroll to the element that should own it.

  1. Scroll chaining. A modal body with overflow: auto scrolls the page behind it once it hits its end, and on mobile triggers pull-to-refresh or the swipe-back gesture. overscroll-behavior: contain on the modal body stops the chaining while keeping the local bounce; none also suppresses the browser's own overscroll affordances.

  2. Layout shift when a scrollbar appears. Classic scrollbars take layout space: about 15px in Chrome on Windows. A route change from short to tall content shifts a centred layout by half that. html { scrollbar-gutter: stable; } reserves the space unconditionally. Overlay scrollbars (macOS, iOS, Android) take none, so this is a no-op there. overflow-y: scroll also prevents the shift, at the cost of a permanently visible disabled track on classic-scrollbar platforms.

  3. text-overflow: ellipsis doing nothing. It needs overflow: hidden (or clip), white-space: nowrap, and a definite width. Miss any one and the text just runs on.

When not to reach for it. overflow: hidden is also a block formatting context, it contains floats and stops margin collapse, which is a legitimate reason to use it, separate from clipping. But it clips descendants only when it is their containing block: an absolutely positioned child whose containing block sits above the clipper paints outside it. When you want clipping with no scroll container and no BFC, overflow: clip (with overflow-clip-margin for a bleed) is the honest tool.

Curated: · Written: · Reviewed:

Q&A-17

Walk me through floats and clearfix: how they work, when they're still the right tool, and what you'd use instead today.

Answer

The 90-second answer. A float takes an element out of normal flow and shifts it to the left or right edge of its containing block, letting inline content wrap around it. Block-level siblings ignore it and can overlap; the parent's height does not include it, so a parent whose children all float collapses to zero height. Clearfix is the historical fix: force the parent to contain its floats. Today, display: flow-root on the parent does that with no side effects, and flexbox or grid should be the default for layout. Floats remain the right tool for exactly one thing: wrapping text around an image or a drop cap.

Mechanism. float: left computes display to block for inline elements. The element is placed at the left edge of its containing block, and subsequent line boxes are shortened to avoid it. Block boxes are laid out as if the float weren't there, but their line boxes are shortened. clear: both on an element moves it down until its top edge is below the bottom margin edge of all relevant floats. The parent collapse happens because floats are out of flow: the parent's height calculation ignores them. If the parent has no other in-flow content, height is 0.

<div class="parent">
  <div class="float">A</div>
  <div class="float">B</div>
</div>
<p>Following content</p>
.parent { background: #eee; }
.float { float: left; width: 100px; height: 100px; }

The parent's computed height is 0, and the <p> overlaps the floats. The classic clearfix:

.parent::after {
  content: "";
  display: table;
  clear: both;
}

The modern equivalent:

.parent { display: flow-root; }

Containment methods compared.

MethodHow it worksSide effects
overflow: hiddenCreates a BFC that contains floatsClips overflow, hides box-shadows and dropdowns, may add scrollbars
overflow: autoSame BFCScrollbars appear if content overflows
::after { clear: both }Pseudo-element clears floatsExtra box; needs display: table or block; no clipping
display: flow-rootCreates a BFC with no other side effectsNone in modern browsers (Safari 13+)
display: flex / gridChildren become flex/grid items; no float neededChanges layout model entirely

When floats are still the right tool. Text wrapping around an image: img { float: left; margin: 0 1rem 1rem 0; }. Flex or grid would put the image and text in separate boxes, not wrap lines around the image. shape-outside for non-rectangular wrap requires a float. Legacy codebases: Bootstrap 3's grid used floats, and you may need to maintain it. Email clients: many don't support flex or grid, so floats and tables remain common.

Failure modes. Parent collapse: detect by inspecting computed height or seeing following content overlap. Fix with display: flow-root. overflow: hidden clipping: a dropdown inside the parent gets cut off; detect by comparing getBoundingClientRect() of the dropdown against the parent. clear: both on an element that shouldn't be cleared pushes it down unexpectedly; detect by layout shift. Floats don't collapse margins with adjacent elements, which can surprise you when converting a float layout to flex.

Modern alternatives. For layout, use flexbox for one-dimensional and grid for two-dimensional. For containing floats, display: flow-root. For text wrap, float is still correct. Don't use floats for page layout unless you're supporting an environment that lacks flex/grid.

Curated: · Written: · Reviewed:

Q&A-20

Walk me through logical properties (margin-inline, padding-block, inline-size) and what actually flips when you set dir="rtl" versus writing-mode: vertical-rl.

Answer

The 90-second answer. A logical property names a side by its job in the flow instead of by a compass direction. The inline axis is the direction text runs; the block axis is the direction successive lines stack. margin-inline-start means "the margin on the edge the text starts from", whatever edge that is. Two switches move it, and they are not the same switch: direction flips the inline axis only, writing-mode rotates both axes.

declarationhorizontal-tb + ltrhorizontal-tb + rtlvertical-rl + ltr
margin-inline-startmargin-leftmargin-rightmargin-top
margin-block-startmargin-topmargin-topmargin-right
padding-block-endpadding-bottompadding-bottompadding-left
inline-sizewidthwidthheight
inset-inline-startleftrighttop

So dir="rtl" on <html> turns every margin-inline-start into a right margin and leaves margin-block-start alone. writing-mode: vertical-rl turns margin-inline-start into a top margin, margin-block-start into a right margin, and inline-size now sets the height.

/* Chrome 121 / Firefox 122 / Safari 17 */
.card {
  padding-block: 12px 20px;        /* top 12, bottom 20 in horizontal-tb */
  padding-inline: 16px;            /* left/right in LTR, right/left in RTL */
  margin-inline-start: 24px;       /* the leading edge, wherever it is */
  border-inline-start: 3px solid #2563eb;
  inline-size: min(100%, 42rem);
}

The trap that bites in review. Mixing physical and logical declarations on the same side:

.bad {
  margin-left: 8px;
  margin-inline-start: 16px;
}
/* LTR: both map to margin-left, later declaration wins → 16px
   RTL: margin-left stays 8px, margin-inline-start becomes margin-right: 16px
   — the two declarations now fight instead of agreeing */

Logical and physical properties that resolve to the same side are ordered by the cascade, so the result depends on source order and on direction. That is the bug you find six months later, not in the PR.

What has no logical equivalent. transform: translateX(-100%), background-position, box-shadow offsets, overflow-x, and 100vw/100vh are all physical. A drawer animated with translateX(-100%) slides off the wrong edge in RTL even when every margin is logical. justify-content: flex-start follows direction; justify-content: left does not.

Detection. Render the page with dir="rtl" and again with writing-mode: vertical-rl in CI, screenshot-diff both, and assert document.documentElement.scrollWidth <= clientWidth. Also prefer :dir(rtl) over [dir="rtl"]: the attribute selector only matches elements that literally carry the attribute, so descendants that inherit direction never match it.

When not to use them. A single-direction product that will stay single-direction gets nothing from logical properties today, and a codebase that mixes both conventions is worse than either one applied consistently. Pick one and enforce it with stylelint-use-logical rather than leaving it to reviewer memory.

Curated: · Written: · Reviewed:

Q&A-19

Walk me through how you'd serve responsive images: srcset, sizes, picture, and aspect-ratio. When does each one apply, and what breaks if you get it wrong?

Answer

The 90-second answer. Three tools, three jobs. srcset + sizes is resolution switching: same image, different pixel widths, and the browser picks one before CSS is parsed. picture is art direction or format negotiation: different crops or AVIF/WebP with a JPEG fallback. aspect-ratio reserves the box so the image doesn't shift layout when it loads. The rule that ties them together: the browser chooses the image from HTML alone, so sizes must be in the markup, not in CSS. If you omit sizes with w descriptors, it defaults to 100vw and you download desktop-sized images on phones.

<img
  src="photo-800.jpg"
  srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1200.jpg 1200w"
  sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33.3vw"
  width="800" height="450"
  alt="A description"
  loading="lazy"
  decoding="async"
>

The browser evaluates sizes to get the slot width, multiplies by the device pixel ratio, then picks the smallest candidate at least that wide, or the largest if none is. On a 375px viewport at DPR 3, the slot is 375px, required is 1125px, so it picks 1200w. On a 1440px viewport at DPR 1, the slot is 33.3vw ≈ 480px, required is 480px, so it picks 800w: 400w is too small. That arithmetic is the whole point: you're giving the browser enough candidates to land near the required width without overshooting.

picture is for when the image itself changes:

<picture>
  <source type="image/avif" srcset="photo.avif 1x, photo-2x.avif 2x">
  <source type="image/webp" srcset="photo.webp 1x, photo-2x.webp 2x">
  <img src="photo.jpg" srcset="photo-2x.jpg 2x" alt="A description" width="800" height="450">
</picture>

The first <source> whose type is supported and whose media matches wins. type is format negotiation; media is art direction: a wide crop on desktop, a tight crop on mobile. The <img> is required: it's the fallback and it carries the alt text. You can put sizes on a <source> to override the <img>'s.

aspect-ratio is the layout half:

.media {
  aspect-ratio: 16 / 9;
  width: 100%;
  height: auto;
  object-fit: cover;
}

It reserves the box before the bytes arrive, so the page doesn't reflow. object-fit: cover crops to fill; contain letterboxes. If you set both width and height, aspect-ratio is ignored. The HTML width and height attributes also give an intrinsic ratio and are read by the preload scanner before CSS loads, so keep them.

Failure modes, and how you catch each.

  1. Missing sizes. With w descriptors and no sizes, the browser assumes 100vw. On a 1440px desktop it may fetch 1200w for a 480px slot. Detect: DevTools Network panel, compare the image's intrinsic width to the rendered width.
  2. srcset for art direction. srcset only swaps resolutions of the same image; it can't change the crop. You need picture with media. Detect: the mobile crop is wrong.
  3. No aspect-ratio or width/height. The image loads and pushes content down. Detect: CLS in Lighthouse, or the layout jumps.
  4. loading="lazy" on the LCP image. It delays the largest paint. Detect: LCP metric; use fetchpriority="high" instead.
  5. sizes with %. Percentages are invalid in sizes; the containing block isn't known at parse time. Use vw, px, em, or calc(). Detect: the browser ignores the invalid entry and falls back to 100vw.

Trade-offs. x descriptors are simpler but ignore layout width; w descriptors are precise but need sizes. picture is more verbose and can't be optimized as aggressively as srcset, so don't use it for plain resolution switching. aspect-ratio replaces the padding-top hack and is supported in all modern browsers; the hack is only for legacy support.

Curated: · Written: · Reviewed:

Q&A-22

Walk me through the CSS you reach for to make a component accessible (focus order, visually hidden text, prefers-reduced-motion and contrast) and the failure each one causes when you get it wrong.

Answer

The 90-second answer. Four different problems, and CSS owns only part of each. Focus order is DOM order: CSS moves boxes, never the tab sequence, so order, flex-direction: row-reverse, grid placement and position: absolute all produce a visual order that diverges from the keyboard order. Visually hidden text has to stay in the accessibility tree and stay focusable, which rules out display: none and visibility: hidden. prefers-reduced-motion asks you to remove vestibular triggers (parallax, large transforms, smooth scrolling) not all feedback. Contrast is arithmetic with a hard threshold: 4.5:1 for body text, 3:1 for text at 24px or 18.66px bold, and 3:1 for the boundary of a UI control (WCAG 2.2 AA, SC 1.4.3 and 1.4.11).

Focus order. Only one CSS-adjacent thing changes tab order, and it is not CSS:

ChangeVisual orderTab order
order: -1 on a flex itemmovesunchanged
flex-direction: row-reversereversedunchanged
position: absolute; top: 0movedunchanged
tabindex="0" on a <div>unchangedinserted at DOM position
tabindex="3"unchangedjumps ahead of everything at 0

Positive tabindex is the one lever that reorders the sequence, and it is almost always the wrong fix: it makes order depend on every other number on the page. If the visual order is wrong, fix the DOM. The related 2.2 failure is a sticky header covering the focused element (SC 2.4.11); scroll-margin-top on focusable targets is the cheap fix.

Visually hidden. display: none and visibility: hidden remove the node from the accessibility tree and from the tab sequence, so a skip link built that way does nothing.

.visually-hidden {
  position: absolute;      /* out of flow: takes no line box */
  width: 1px; height: 1px; /* not 0 — some AT drops zero-size nodes */
  margin: -1px; overflow: hidden;
  clip-path: inset(50%);   /* replaces the deprecated clip: rect(0 0 0 0) */
  white-space: nowrap;     /* stops the 1px box wrapping into a tall column */
  border: 0; padding: 0;
}
.skip-link:focus { position: static; width: auto; height: auto; clip-path: none; }

Contrast. Relative luminance linearises each sRGB channel: c/12.92 below 0.03928, else ((c+0.055)/1.055)^2.4, then L = 0.2126R + 0.7152G + 0.0722B, and the ratio is (L1+0.05)/(L2+0.05). On white, #767676 gives L ≈ 0.181 and 1.05/0.231 = 4.54:1, which passes; #777777 gives L ≈ 0.1845 and 4.48:1, which fails. That one-hex-step boundary is why grey-on-white body text is the most common AA failure in the wild. The number is computed on rendered colour, so opacity, rgba() text over a gradient, and text over a background image are where it silently breaks: devtools' checker only reads the computed background-color.

Reduced motion. It is a media query, so it reacts live to the OS setting with no JS:

@media (prefers-reduced-motion: reduce) {
  .parallax, .hero-slide { animation: none; transform: none; }
  html { scroll-behavior: auto; }
  .fade { transition-duration: 120ms; } /* opacity is fine; movement is not */
}

The blanket * { animation-duration: 0.01ms !important } reset is popular and wrong in one direction: it also kills the spinner that tells a user their upload is still running. Scope it to transforms and scroll behaviour, keep opacity fades.

Failure modes and how you catch each. outline: none on :focus: tab through the page for thirty seconds and watch the focus ring vanish; use :focus-visible instead so mouse clicks stay quiet. order mismatch: tab through and watch focus jump backwards across the screen. A hidden label built with display: none: inspect the accessibility tree in devtools and the name is empty. None of these are caught by a build; they are caught by a keyboard pass and a screen-reader pass on the component before it ships.

Curated: · Written: · Reviewed:

Q&A-24

Walk me through how you'd ship a layout built on a modern CSS feature to browsers that don't support it: feature queries, vendor prefixes, and where progressive enhancement fits.

Answer

The 90-second answer. Ship a baseline that works without the feature, then add the feature inside a feature query. The baseline is plain CSS every browser in your support matrix parses; the enhancement sits in @supports, which the browser evaluates at parse time and drops whole if the condition is false. Order matters: the fallback rule comes first, the @supports block after, because both have the same specificity and the later declaration wins.

/* Baseline — no detection, works everywhere. */
.card-list { display: flex; flex-wrap: wrap; margin: -0.5rem; }
.card      { flex: 1 1 18rem; margin: 0.5rem; }

/* Enhancement — dropped whole by any browser that fails the query. */
@supports (display: grid) and (gap: 1rem) {
  .card-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr));
    gap: 1rem;
    margin: 0;
  }
  .card { margin: 0; }
}

Trace it: a browser that parses both blocks applies display: flex, then overrides it with display: grid. Same specificity (0,1,0), later wins. A browser that fails the query never sees the second block, so flex stands. No user-agent string is read anywhere.

What each detection tool actually covers.

DetectingHowCaveat
Property/value support@supports (display: grid)Parses the declaration; false only if the browser drops it
Selector support@supports selector(:has(> img))Bare :has() is invalid inside @supports; selector() is required
Support from JSCSS.supports('display', 'grid')Same engine check, usable to gate a script
A prefixed property@supports (-webkit-line-clamp: 2)Works: @supports parses prefixed declarations too
HTML/JS featuresNot @supportsHTMLScriptElement.supports('module'), <picture>/srcset

Vendor prefixes. Prefixes are a build concern, not a hand-written one: Autoprefixer driven by a browserslist entry (> 0.5%, last 2 versions, not dead) adds exactly the prefixes your matrix needs. Write the prefixed declaration first and the standard one second so the standard wins where both parse. A handful still earn their place in 2025: -webkit-line-clamp for multi-line truncation, -webkit-text-size-adjust: 100% against iOS text inflation, and -webkit-backdrop-filter for Safari before 18, which shipped the unprefixed property in 2024.

Failure modes, and how you catch each.

  1. The query passes, the behaviour doesn't. Safari 14.1 added gap for flex containers; before that, gap parsed as a grid property, so @supports (gap: 1rem) returned true while gap on a flex container did nothing. @supports tests syntax, never behaviour. Catch it with a visual regression run on real WebKit, not a Chromium-only CI.
  2. The fallback disappears with the enhancement. IE11 has no @supports at all, so @supports not (display: grid) { … } is dropped along with everything else. The fallback must live outside the at-rule. Catch it by loading the page in the oldest engine you claim to support.
  3. UA sniffing picks the wrong branch. Chrome froze and reduced its UA string and Safari's is frozen too, so version parsing silently misroutes. Catch it by grepping the codebase for navigator.userAgent in a lint rule.
  4. The fallback rots. Nobody runs it, so it drifts out of sync with the enhanced path. Catch it with a Playwright project that forces the baseline (a no-supports build flag) on every PR.

When not to. If the feature is Baseline widely available and your matrix is evergreen-only, ship it plain. Every @supports block is a second code path you now own, and the fallback is the one that gets tested least.

Curated: · Written: · Reviewed:

Q&A-21

A page's INP is 400 ms and a Performance recording shows layout blocks between every style write. Walk me through how you'd use will-change, contain, content-visibility and critical CSS here, and what each one costs you.

Answer

The 90-second answer. Ask which metric is slow first, because these four levers fix different ones. Layout thrashing is an INP problem: reading a layout property after a write forces the browser to flush style and layout synchronously, so a loop that alternates read and write does N full layouts instead of one. will-change and contain are invalidation levers: they shrink the set of things a change can dirty. content-visibility: auto skips rendering work for off-screen subtrees, which is a load and scroll-cost lever. Critical CSS is an LCP lever: it removes a round trip from first paint.

Layout thrashing. The browser batches writes and flushes them lazily before paint. Reading offsetWidth, offsetHeight, getBoundingClientRect(), scrollTop or getComputedStyle() forces that flush early. Interleaved with writes, every read pays for a full style + layout pass.

// 100 reads, 100 forced layouts
for (const el of items) el.style.width = el.offsetWidth + 10 + 'px';

// all reads, then all writes — one layout
const widths = items.map(el => el.offsetWidth);
items.forEach((el, i) => { el.style.width = widths[i] + 10 + 'px'; });

On a mid-range Android, a forced layout of a 2,000-node tree runs 5–20 ms; a hundred of them is a 500 ms–2 s long task, which is exactly the INP cliff. Detect it in a Performance recording as purple Layout blocks interleaved with Recalculate Style, or the console's "Forced reflow" warning.

will-change. It tells the compositor to promote the element to its own layer ahead of time, so an animation doesn't repaint the parent. The cost is real: each layer is a GPU texture, and a 400×300 element at DPR 3 is 1200×900×4 bytes ≈ 4.3 MB. Promote fifty rows and you've spent ~200 MB of GPU memory and made the page slower. It also creates a stacking context and a containing block for fixed/absolute descendants: the same trap as transform. Apply it shortly before the animation and remove it after; never leave it in a stylesheet as a default.

contain. Each value cuts a different dependency edge:

valueisolateswhat it breaks
layoutinternal layout can't affect outsidebecomes containing block for abs/fixed
paintdescendants clipped to the boxoverflow: visible no longer works
sizeelement size independent of contentscollapses to 0 without an explicit size
stylecounters and quotes don't escaperarely what you want

contain: content is layout paint style. Reach for it on repeated components (cards, list rows) where you know nothing escapes the box.

content-visibility: auto. It implies contain: layout style paint plus size containment while the element is skipped, and skips style, layout and paint for the subtree. Without contain-intrinsic-size the element measures 0 while skipped, so the scrollbar jumps and CLS spikes. auto remembers the last rendered size:

.card { content-visibility: auto; contain-intrinsic-size: auto 500px; }

Chrome 85+, Firefox 125+, Safari 18+. On a long article page with 200 off-screen cards, Chrome typically drops initial rendering time by 40–60% in the lab: a figure that moves with content, so measure your own page.

Critical CSS. Inline the above-the-fold CSS in a <style> in <head> and load the rest with <link rel="preload" as="style" onload="this.rel='stylesheet'">. The budget is the initial congestion window: ~10 TCP segments × 1460 bytes ≈ 14 KB, so anything inlined under that arrives in the first round trip. On a 100 ms RTT connection that is 100 ms off first paint. The failure mode is drift: the inlined block and the full sheet diverge and you get FOUC on routes nobody tested. Generate it at build time (Critters, Penthouse) and assert in CI that the inlined block is a subset of the full sheet.

What I'd actually do here. Fix the read/write interleaving first; it is free and usually the whole 400 ms. Then add contain: content to the repeated components. Only then reach for will-change on the one element that animates, and content-visibility on the long off-screen list.

Curated: · Written: · Reviewed:

Q&A-23

Walk me through how you'd choose a CSS architecture for a large codebase (BEM, CSS Modules, utility-first, cascade layers) and how you keep specificity from drifting over time?

Answer

The 90-second answer. These are two problems, not one. CSS has a single global namespace and a single cascade, so at scale you need a naming strategy (collisions) and a specificity strategy (drift). BEM and CSS Modules attack the first; utility-first and cascade layers attack the second. Most large codebases end up running two of them together.

Ask what the constraint is before picking. A design system consumed by other teams values encapsulation over authoring speed. A product surface with a small team and a token system values velocity, and utility-first wins there. A codebase with a decade of legacy CSS values adoption cost above all, and that points at layers.

EncapsulationSpecificity ceilingBuild stepRefactor safety
BEMconvention only0,1,0 if disciplinednonegrep, unreliable with dynamic names
CSS Modulesbuild-time hash0,1,0bundlerrename is a compile error
Utility-firstnone needed0,1,0 by constructionTailwindclass strings, no rename
Cascade layersordering, not scopinglayer order beats specificitynone, nativeadditive, safe to introduce
/* layer order is set by first appearance, not by specificity */
@layer reset, tokens, base, components, utilities;

@layer reset {
  /* :where() contributes zero specificity, so this never fights anything */
  :where(h1, h2, h3) { margin: 0; }
}

@layer components {
  .card { padding: 1rem; }
  .card--featured { border: 2px solid; } /* still 0,1,0 */
}

/* unlayered: outranks every layered normal declaration above */
.card { padding: 2rem; }

That last rule is the one that bites. Unlayered normal declarations beat layered ones regardless of specificity: the spec treats them as an implicit final layer. !important reverses the whole thing: important declarations in layers beat important unlayered ones, and among importants the earlier layer wins. So a legacy !important sitting in unlayered CSS is still at the top of the pile. Cascade layers shipped in Chrome 99, Firefox 97 and Safari 15.4, all in the first half of 2022.

Failure modes, and how you catch each.

  1. Specificity creep. A bug gets fixed with a longer selector, then !important, then a second !important to beat the first. Detect with stylelint's no-descending-specificity plus a CI job that reports the max specificity per stylesheet. Fix by moving the offending file into a layer, not by writing a longer selector.
  2. Layer inversion on adoption. You wrap new code in @layer while legacy stays unlayered, so legacy now wins everywhere it overlaps. Detect with screenshot diffing in CI. Fix by putting legacy in @layer legacy before you layer anything else, so the order is declared up front.
  3. Dead CSS. Chrome DevTools' Coverage panel shows what a page load actually used; PurgeCSS or Tailwind's content scan does it at build time. Grep is not a detector: styles[btn-${variant}] hides usage from it completely.
  4. Third-party CSS you can't edit. Import it into a layer: @import url("vendor.css") layer(vendor);. Your unlayered styles then win without a single !important.

When not to. Utility-first in a component library that consumers must theme: you are shipping your class names as public API and every rename is a breaking change. BEM in a codebase with heavy dynamic composition: the convention has no compiler behind it, so it decays the first time someone is in a hurry.

Curated: · Written: · Reviewed:

Q&A-25

You've inherited a 40k-line legacy stylesheet and a new design system. How do you migrate components onto it without breaking layout in production?

Answer

The 90-second answer. Don't rewrite. Make the cascade deterministic first, then migrate one component at a time behind a visual-regression gate. If you start by editing rules, every change is a fight with specificity you can't see. If you start by putting the legacy sheet into a cascade layer, the design system wins by layer order rather than by specificity, and each migration becomes a local edit you can review.

1. Freeze and measure. Capture a baseline before touching anything: a visual regression run over your top routes at two viewports. Then count what you're actually replacing: distinct colors, distinct spacing values, !important count. A real legacy sheet usually carries 40-odd greys and 30-odd spacing values. That count is the size of the job, and it's the number you show whoever asks for a date.

2. Layer it.

/* entry.css */
@layer reset, legacy, ds, overrides;

@import url("legacy.css") layer(legacy);
@import url("design-system.css") layer(ds);

The gotcha that decides the whole plan: unlayered styles beat every layered style, whatever their specificity. A stray <style> block, an inline style= attribute, or a third-party widget's stylesheet that you never wrapped still outranks the design system. Audit for those before you migrate anything, or you'll spend a week debugging a rule that loses to something you can't see in your own repo. revert-layer is the escape hatch when one component needs to opt back out.

3. Tokenize before you restyle. Swap literal values in the legacy sheet for custom properties set to their current values. Nothing moves; the visual diff is empty. Then change the token values once, in one place, and the diff shows you exactly what that change costs across the whole app. This is the highest-leverage move available: it turns "restyle 200 components" into "change 9 values and review one diff."

4. Migrate leaf-first. Buttons, badges, inputs before page shells: leaves have fewer ancestors whose layout they can disturb. One component per PR, one visual diff, and the legacy rules deleted in the same PR. Leaving both alive is how you end up with two sources of truth and no way to tell which one is winning.

5. Delete. CSS coverage in DevTools over a full crawl, plus a grep for dynamically composed names like `btn-${variant}`. A naive grep calls a rule dead when it's built at runtime.

FailureSymptomDetection
Unlayered legacy or inline <style>DS rule loses despite lower specificityComputed pane shows legacy winning; grep for <style and style=
Token swap changes unitsrem↔px, unitless line-height → pxVisual diff on long-form text, not just components
Deleting runtime-composed classesOne variant unstyled, others fineCoverage over a crawl that exercises every variant
Baseline captured on a broken stateSuite green while the bug shipsReview baseline images, not just the diff count

Cost. 300 routes × 2 viewports × 3 browsers is 1,800 screenshots per run; at ~1.5 s each that's ~45 minutes serial. Shard it, or gate only the routes a PR touches and run the full sweep nightly.

Curated: · Written: · Reviewed: