Overview
Curated: · Written: · Reviewed:
CSS fundamentals and layout
CSS interviews are not about remembering property names. They are about the layout algorithm: which box an element generates, which declaration wins for a given property, what containing block it resolves against, and how it sizes when space is constrained. Almost every 'why is this not centered' or 'why is my z-index ignored' question is one of those four going differently than you assumed.
The mental model to carry: the browser turns the DOM into boxes, resolves every declaration through the cascade down to one computed value per property, then runs a layout algorithm that assigns each box a position and size inside its containing block. Debugging CSS is finding which of those three steps disagreed with you.
CSS fails silently. There is no exception, no stack trace, no type error. A misspelled property is dropped; a losing declaration is simply not applied. Senior interviews lean on this because it tests whether you can reason about a system with global, order-dependent rules and no runtime feedback.
Why CSS layout decisions are interview material
Layout bugs are expensive to diagnose because the cause is usually several levels away from the symptom. A misaligned card is often a min-width: auto on a flex item, not the card. A hidden dropdown is a stacking context created by an ancestor's transform, not the dropdown's z-index. A table that scrolls the whole page sideways is usually an element with overflow left at visible somewhere up the tree.
What gets probed at senior level:
- Box model arithmetic: can you compute the rendered size of a box from its declarations?
- Cascade resolution: given two competing rules, which wins and why?
- Flex vs Grid choice: can you justify the pick, not just produce a working layout?
- Stacking contexts: why
z-index: 9999did nothing. - Flow and floats: what a float removes from normal flow, and what it does to its parent's height.
- Overflow and scroll containers: which value creates a scroll container and which only clips.
- Writing modes and logical properties: what breaks in a right-to-left build.
- Responsive strategy: breakpoints, fluid sizing, and when a container query beats a media query.
- Debugging method: what you open in devtools first, and what you look at.
Trivia such as 'name the position values' is a warm-up. The question is the trade-off behind the value.
The box model and box-sizing
Every element generates a box with four rings: content, padding, border, margin. width and height apply to the content box by default, because the initial value of box-sizing is content-box. Switch to border-box and the declared size includes padding and border, so the content shrinks to fit.
Work the arithmetic on one box:
.box { width: 300px; padding: 16px; border: 2px solid; margin: 8px; }
| content-box (default) | border-box | |
|---|---|---|
Declared width | 300px | 300px |
| Content width | 300px | 300 - 32 - 4 = 264px |
| Rendered outer width | 300 + 32 + 4 = 336px | 300px |
| Space occupied incl. margins | 336 + 16 = 352px | 300 + 16 = 316px |
That 36px gap between the two columns is the reason nearly every codebase ships this reset:
*, *::before, *::after { box-sizing: border-box; }
Margin collapsing is the other box-model trap. Adjacent vertical margins between in-flow block boxes collapse to the larger of the two, not the sum. A 20px bottom margin meeting a 30px top margin produces 30px, not 50px. Parent and child margins collapse too: a child's top margin can push the parent down, which is why a heading shows a gap above its container. Collapsing does not occur for flex items, grid items, floats, absolutely positioned boxes, or when padding, a border, or an overflow value other than visible separates the two margins. To stop it, add padding or overflow: hidden to the parent, or make the parent a flex or grid container.
Cascade, specificity, and inheritance
The cascade picks one winning declaration per property. It compares, in order: origin and importance, then cascade layers, then specificity, then order of appearance. Only the first tie-breaker that differs decides.
Origin and importance, lowest to highest priority:
- Normal user-agent styles
- Normal user styles
- Normal author styles
- Animations
- Important author (
!important) - Important user
- Important user-agent
- Transitions
Two consequences worth stating in an interview: a user's !important beats your !important, and an author !important beats an inline style. !important is a specific rung on a ladder, not a trump card.
Layers (@layer) sit between origin and specificity. For normal declarations, unlayered styles beat layered ones, and later layers beat earlier ones. For !important declarations the order reverses: layered important beats unlayered important, and earlier layers beat later ones. Layers let a design system ship low-priority defaults without specificity wars.
Specificity is a three-part score (a, b, c):
a: ID selectorsb: classes, attribute selectors, pseudo-classesc: type selectors and pseudo-elements
Inline styles sit above all selectors but below !important. Two modern gotchas: :where() contributes zero specificity, while :is() and :not() take the specificity of their most specific argument. So :where(.btn) is a free override hook, and :is(#a, .b) scores as an ID.
Run the comparison on a real conflict:
.card { color: gray; } /* (0,1,0) */
.card.featured { color: black; } /* (0,2,0) */
#hero .card { color: red; } /* (1,0,0) */
#hero .card wins on the a column before b or c are compared. Adding more classes to the second rule cannot beat it: only another ID, an inline style, or !important can.
Inheritance is separate from the cascade. Inherited properties (mostly text: color, font-*, line-height, visibility, cursor, list-style) flow from parent to child when no declaration targets the child. Non-inherited properties (margin, padding, border, width, height, background, display) do not. The four explicit keywords: inherit forces the parent's computed value, initial resets to the property's spec default, unset behaves as inherit for inherited properties and initial otherwise, and revert rolls back to the previous origin's value, which is useful for undoing a reset.
Flexbox vs Grid: choosing the right layout system
Flexbox is one-dimensional: it distributes space along a single axis and lets items size to content on the cross axis. Grid is two-dimensional: you define tracks on both axes and place items into them. The decision rule is the shape of the content, not personal preference.
- Flexbox: a row of buttons, a toolbar, a nav bar, a card whose footer sticks to the bottom. Content determines size; the container distributes leftover space.
- Grid: a page shell, a dashboard, a gallery, a form with aligned label and field columns. The container determines the tracks; content fills them.
They compose. A grid page shell with flex toolbars inside is normal.
The flex shorthand is where most candidates get caught:
flex: 1; /* 1 1 0% : grow, shrink, basis zero: equal shares */
flex: auto; /* 1 1 auto : grow, shrink, basis content: size to content first */
flex: none; /* 0 0 auto : fixed at content size */
With flex: 1, two items split the row 50/50 regardless of their text. With flex: auto, the item with more content starts wider and only the leftover space is shared.
The classic flex bug: a flex item's min-width defaults to auto, which means it refuses to shrink below its min-content size. A long unbreakable string or a wide table blows out the container no matter how small you set flex-shrink. The fix is one line:
.main { flex: 1; min-width: 0; } /* or overflow: hidden */
Grid's most useful pattern is the responsive gallery without media queries:
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 16px; }
auto-fill keeps empty tracks; auto-fit collapses them so existing items stretch. That one-word difference is a common follow-up.
Positioning and stacking contexts
Five values for position:
static: the default;top,leftandz-indexdo nothing.relative: offsets from its normal position, leaving the original space occupied. Mostly used to establish a containing block.absolute: removed from flow, positioned against its nearest positioned ancestor (any ancestor whosepositionis notstatic).fixed: positioned against the viewport, unless an ancestor hastransform,filter,perspective,contain, orwill-changeset, in which case that ancestor becomes the containing block. This is why a modal 'fixed' to the viewport scrolls with its parent.sticky: behaves asrelativeuntil the nearest scrolling ancestor crosses a threshold, then sticks. It needs a scrollable ancestor and atop,bottom,leftorrightvalue to do anything.
Stacking contexts are why z-index: 9999 sometimes loses. z-index applies only to positioned elements and to flex and grid items. A new stacking context is created by, among others: the root element, position other than static combined with z-index other than auto, opacity less than 1, transform, filter, will-change, isolation: isolate, and contain: paint.
Trace the trap:
<div class='a' style='position: relative; z-index: 1'>
<div class='tooltip' style='position: absolute; z-index: 9999'>...</div>
</div>
<div class='b' style='position: relative; z-index: 2'>...</div>
The tooltip's 9999 is compared only against its siblings inside .a's stacking context. .a sits at 1, below .b at 2, so the tooltip paints under .b despite the larger number. Raise .a, or remove whatever property created the context in the first place.
Display, inline formatting, and floats
The display value sets the outer and inner box type. block boxes stack vertically and take the full available width. inline boxes flow within a line and ignore width and height. inline-block flows in a line but accepts sizing. inline-grid and inline-flex do the same for their respective layout models: the container sits in the line box, aligns to the baseline of the surrounding text, and gets shrink-to-fit width when its width is auto.
A dashboard tile declared as display: inline-grid therefore does not stack under the previous tile. It flows beside it and picks up baseline gaps from the line box. Switching to display: grid makes it block-level, or the tiles can be wrapped in a flex or grid parent.
Floats (float: left or right) are removed from normal flow. Line boxes wrap around them, but the block boxes around them ignore them. The parent does not grow to contain a float, so a parent with a fixed height and floated children behaves as if the children were not there when it comes to its own height. For a sidebar with float: left; width: 200px; height: 300px followed by a .content block, the content wraps beside the sidebar, and the sidebar can overflow the bottom of a parent that has no containing mechanism.
Fix options, in order of modernity: make the parent a flex or grid container, give the parent display: flow-root (or any overflow other than visible, which also creates a block formatting context), or use clear on the following element. Floats remain valid for text wrapping around an image; for page layout they have been superseded.
Overflow and scroll containers
overflow decides what happens to content that does not fit the box, and whether the box becomes a scroll container.
| Value | Content outside the box | Scroll container | Scrollbars |
|---|---|---|---|
visible | Painted outside, default | No | None |
hidden | Clipped | Yes, programmatically scrollable, no user scrolling | None |
clip | Clipped | No | None |
scroll | Clipped, scrollable | Yes | Always shown |
auto | Clipped, scrollable | Yes | Shown when content overflows |
hidden, scroll and auto also create a block formatting context, which is why overflow: hidden on a parent stops child margins from collapsing through it. clip does neither. That difference matters when you want to clip without changing scroll or margin behavior.
Two computation rules: if one axis is not visible, a visible value on the other axis computes to auto. And clip on one axis becomes hidden when the other axis is not visible. So a filter list written as .list { width: 320px; box-sizing: border-box; overflow-y: auto; } has overflow-x computed to auto as well. A horizontal scrollbar appears only if its content is wider than 320px, and box-sizing: border-box keeps any padding inside that 320px.
Writing modes, direction, and logical properties
Physical properties (margin-left, padding-right, text-align: left) name a screen side. Logical properties name a flow direction: margin-inline-start, padding-block-end, text-align: start. With dir='rtl' on <html>, the inline axis runs right to left. A physical margin-left: 16px stays on the left, so a card rendered in an RTL build keeps its spacing on the wrong side while its text reverses.
Flex containers follow direction too. flex-direction: row lays items out right to left under dir='rtl', so a justify-content: flex-start toolbar moves to the right edge. Using logical properties and start/end values means one stylesheet serves both LTR and RTL builds, and the same card component works under either direction without per-locale overrides.
When you need an RTL override, scope it to the attribute or language ([dir='rtl'] .x, :dir(rtl)), not to a global class that a future LTR screen might also use.
Custom properties, transitions and animation
Custom properties (--name) are inherited and resolved at computed-value time. An invalid substitution does not throw. It makes the declaration invalid at computed-value time, and the property falls back to its inherited value (for inherited properties) or its initial value (for others).
Trace a common case:
:root { --motion: 500; }
.toast { transition-duration: var(--motion); }
500 has no unit, so it is not a valid <time>. The substitution produces transition-duration: 500, which is invalid at computed-value time. transition-duration is not inherited, so it takes its initial value of 0s, and the toast has no transition at all. Writing --motion: 500ms fixes it, or calc() with units.
Custom properties also do not animate by default. A change to --x from one value to another does not produce a transition on background if the browser has no registered syntax for it. Registering the property with @property --x { syntax: '<length>'; inherits: false; initial-value: 0px; } gives the browser a type, so it can interpolate the value. Without registration, the declaration changes instantly.
Transitions and animations are separate from each other. A transition runs when a computed value changes between two states. A keyframe animation runs from its own timeline and can be applied independently of style changes. In the cascade, animation declarations sit above normal author styles and below important author styles, so an animated value can be overridden by an !important rule.
Responsive design, media queries, and container queries
Mobile-first means writing the base styles for the smallest viewport and adding min-width media queries upward. max-width queries work but invert the mental model and tend to accumulate overrides.
@media (min-width: 768px) { .nav { display: flex; } }
Container queries let a component respond to its own container's size rather than the viewport, which is what you want for reusable components dropped into different slots.
.card-wrap { container-type: inline-size; }
@container (min-width: 400px) {
.card { display: grid; grid-template-columns: 120px 1fr; }
}
container-type: inline-size establishes the query container on the inline axis, so the component adapts wherever it is placed. Container queries are baseline-available across current browsers, so 'use a media query instead' is no longer the default answer for component-level responsiveness. Media queries still decide page-level shell changes, such as whether the navigation is a sidebar or a drawer.
For fluid sizing, clamp() replaces a stack of breakpoints:
h1 { font-size: clamp(1.5rem, 2vw + 1rem, 3rem); }
That reads: never smaller than 1.5rem, never larger than 3rem, scale with the viewport in between.
Units, viewport, and intrinsic sizing
| Unit | Relative to | Watch out for |
|---|---|---|
px | Device-independent pixel | Not a physical pixel; scales with zoom |
em | Element's own font-size (parent's, when setting font-size) | Compounds through nesting |
rem | Root font-size (16px default) | Predictable; the safe default for spacing |
% | Parent's corresponding dimension | Height percentages need a definite parent height |
vw / vh | 1% of viewport width / height | 100vh on mobile can hide content behind the URL bar |
dvh / svh / lvh | Dynamic / small / large viewport height | Use dvh for full-height mobile layouts |
ch | Width of the 0 glyph | Useful for measure-constrained text |
fr | Free space in a grid track | Only valid in grid |
The em gotcha: when em sets font-size, it resolves against the parent's font-size; on any other property it resolves against the element's own font-size. Nested em font sizes multiply, which is why rem is the safer default for spacing scales.
Intrinsic sizing keywords describe what a box wants before the container constrains it:
min-content: the smallest the box can be without overflowing (longest unbreakable word).max-content: the size with no wrapping at all.fit-content:min(max-content, max(min-content, available)).
These are the values behind min-width: auto on flex items, and behind grid-template-columns: minmax(0, 1fr) when a grid track refuses to shrink.
Scroll snapping and carousels
A horizontal product carousel is a flex row inside an overflow-x container. Scroll snapping controls where the scroll position comes to rest.
.carousel { display: flex; overflow-x: auto; scroll-snap-type: x mandatory; gap: 16px; }
.carousel > .card { flex: 0 0 240px; scroll-snap-align: start; }
scroll-snap-type goes on the scroll container, and scroll-snap-align goes on the children. mandatory always snaps to a point after scrolling ends; proximity snaps only when a point is near. flex: 0 0 240px stops the cards from shrinking when the row overflows, which is the usual reason a carousel's cards squash instead of scrolling. Each card's content, such as a star icon with a rating number, should carry its value as text or an accessible label, not as an icon alone, so the rating survives when the icon is hidden or the card is read by assistive technology.
Rendering cost of style writes in loops
Writing styles is cheap until something forces the browser to compute layout synchronously. Compare two loops over a 500-row table:
// Writes only: style changes are batched, one layout at the next frame.
rows.forEach((row) => { row.style.width = targetWidth + 'px'; });
// Read after write: each read of offsetWidth forces a synchronous layout.
rows.forEach((row) => {
row.style.width = targetWidth + 'px';
const w = row.offsetWidth; // forces layout on every iteration
});
The second pattern is layout thrashing. The fix is to batch reads before writes, or to change a single class on a parent instead of 500 inline styles. Whether this matters in practice depends on how many elements are touched and how much of the page they affect, so measure in the Performance panel before optimizing.
Debugging layout: devtools, common failure modes
Open the Computed tab, not the Styles tab, when a value is not what you expect: it shows the resolved value and which rule won. The box model diagram shows the four rings with live numbers, which settles any box-sizing argument in seconds. The flex and grid overlays draw track lines and gaps directly on the page.
For a quick visual pass, outline is the right tool because it does not affect layout:
* { outline: 1px solid red; } /* border would change the box; outline does not */
Common failure modes and their real causes:
| Symptom | Actual cause | Fix |
|---|---|---|
z-index ignored | Element is static, or an ancestor created a stacking context | Position the element, or raise the ancestor |
| Flex item overflows | min-width: auto on the item | min-width: 0 |
| Grid track won't shrink | Track minimum is auto | minmax(0, 1fr) |
| Gap above a container | Child's top margin collapsed through the parent | Padding, overflow: hidden or display: flow-root on the parent |
| Parent height ignores children | Children are floated | display: flow-root on the parent, or flex/grid |
| Horizontal scrollbar appears | Child content wider than an overflow-x: auto container, or overflow-y set without overflow-x | Constrain the child, or set both axes deliberately |
100vh overflows on mobile | vh ignores the collapsing URL bar | 100dvh |
| 'Fixed' element scrolls | Ancestor has transform or filter | Move the element out of that subtree |
margin: auto won't center | Parent has no definite width, or the element is not block-level | Give the parent a width, or use flex/grid centering |
| Transition does not run on a custom property | Property not registered with @property | Register it with a syntax |
What interviewers probe and weak answers
Typical probes, and what separates a strong answer from a weak one:
- 'What does
box-sizing: border-boxchange?' Strong: it moves padding and border inside the declared width, so the rendered outer size equals the declared size. Weak: 'it makes sizing easier.' - 'Why is my
z-indexnot working?' Strong:z-indexneeds a positioned element, and a new stacking context on an ancestor traps the value. Weak: 'raise the number' or 'add!important.' - 'Flexbox or Grid for this layout?' Strong: names the axis count and the sizing source (content or container). Weak: 'Grid is newer, so use Grid.'
- 'How do you make this component responsive?' Strong: distinguishes viewport-driven (media query) from container-driven (container query) and picks based on reuse. Weak: lists breakpoints without saying why.
- 'Why does this flex child overflow?' Strong:
min-width: autoand min-content sizing. Weak: 'addoverflow: hidden' without knowing why it works. - 'What does
overflow: hiddendo besides clipping?' Strong: it makes the element a scroll container and a block formatting context, which changes margin collapsing. Weak: 'it hides the overflow.' - 'Why did my float push the parent's background out of place?' Strong: floats leave normal flow and the parent does not contain them, so its height ignores them. Weak: 'use clearfix' with no explanation.
- 'Why does the layout break in an RTL build?' Strong: physical properties do not flip; logical properties and
start/endvalues do. Weak: 'add a second stylesheet.' - '
emvsrem?' Strong:remis root-relative and predictable;emcompounds and is useful for component-relative scaling. Weak: 'remis better.'
A weak answer describes what a property does. A strong answer describes the rule that decides the outcome, names the failure mode, and says when the other choice would be right.