CSS interview questions and answers, from the box model to container queries

CSS interview questions check whether you can predict what the browser will draw: the box model and box-sizing, how specificity, source order and cascade layers decide which rule wins, flexbox versus grid, positioning, why z-index sometimes does nothing, and how to build responsive layouts with media and container queries. Senior rounds add rendering performance and CSS architecture. The strongest answers explain the rule behind the bug, not only the property that fixed it.

By Published 9 min read

How CSS shows up in interviews

Frontend and UI engineering interviews test CSS in three ways. There are concept questions (specificity, box model, positioning). There are build tasks: recreate a card, a navigation bar or a responsive grid from a screenshot in a shared editor. And there are debugging prompts: a sticky header that does not stick, a modal hidden behind a dropdown, text overflowing a flex row. Many candidates who are strong in JavaScript stumble here, so a clear CSS round can set you apart.

  1. Concept questionsBox model, selectors, specificity, display values, units.
  2. Layout buildImplement a design with flexbox or grid, responsive at two or three widths.
  3. Debugging and architectureFind why a rule does not apply, why a layer sits on top, how you organize styles in a large codebase.

Fundamentals: box model, units and inheritance

Basic CSS interview questions
QuestionWhat it testsWhat a strong answer shows
Explain the box model.Layout basicsEvery box has content, padding, border and margin. With the default content-box, width sets only the content, so padding and border add to it; border-box includes them, which is why most resets apply it to everything.
What is margin collapsing?Block layoutAdjacent vertical margins of block boxes in normal flow combine into the larger one. It does not happen in flex or grid containers, or when padding, a border or a new formatting context separates them.
display: none versus visibility: hidden versus opacity: 0?Renderingnone removes the box from layout and the accessibility tree; hidden keeps the space but hides it from view and assistive technology; opacity 0 keeps space and stays interactive and readable by screen readers.
inline, block and inline-block?Display valuesInline boxes flow in text and ignore width and height; block boxes take the full line; inline-block flows inline but accepts width, height and vertical margins, and its padding pushes neighboring lines away.
px, em, rem, %, vw: when do you use each?Unitsrem for type and spacing tied to the root font size, em for things that should scale with their own text, % for sizes relative to the container, viewport units for full-screen sections; px for hairlines and borders.
Which properties inherit?InheritanceMostly text-related ones: color, font, line-height, visibility. Box properties such as margin, padding, border and background do not.
inherit, initial, unset, revert: what is the difference?Global keywordsinherit copies the parent's value; initial uses the property's spec default; unset acts as inherit for inherited properties and initial otherwise; revert rolls back to the browser's own stylesheet value.
What does clamp() do?Fluid sizingclamp(min, preferred, max) keeps a value between bounds, such as font-size: clamp(1rem, 2.5vw, 2rem) for type that scales with the viewport but never gets unreadable.
What are custom properties, and how do they differ from preprocessor variables?Modern CSSThey are real properties that inherit through the DOM and can change at runtime (per theme, per component, from script). Sass variables are compiled away before the browser sees the file.
What is a block formatting context?Layout internalsAn isolated layout region; floats do not leak out and margins do not collapse across it. display: flow-root creates one without side effects.
Basic CSS interview questions. Scroll sideways on a small screen.

Specificity and the cascade

Interviewers love to ask which rule wins. Specificity is counted in three columns: IDs, then classes, attributes and pseudo-classes, then elements and pseudo-elements. Compare column by column from the left; one ID beats any number of classes. Inline styles sit above all selectors, and !important flips the order of origins.

/* <nav id="main-nav" class="menu"><a class="link active" href="/">Home</a></nav> */

#main-nav a        { color: blue;   }  /* (1, 0, 1) */
.menu .link.active { color: green;  }  /* (0, 3, 0) */
nav a:hover        { color: orange; }  /* (0, 1, 2) when hovered */
a.link             { color: purple; }  /* (0, 1, 1) */

/* Result: blue. One ID outweighs three classes.
   :where() adds nothing to specificity; :is() and :not() take
   the specificity of their most specific argument. */
:where(#main-nav) a { color: red; }    /* (0, 0, 1), loses to all of the above */
Which color does the link get? Specificity worked out by hand in the comments as (IDs, classes, elements). Not rendered for this page.
  • What is the full order the cascade uses? Origin and importance first (user agent, user, author; important declarations reverse that order), then cascade layers, then specificity, then order of appearance. Scoping and inline styles also sit in this chain.
  • What are cascade layers? @layer lets you declare named layers, such as reset, base, components and utilities, in a fixed order. A later layer beats an earlier one regardless of specificity, so a utility class can override a component's complex selector without a specificity war.
  • Do unlayered styles beat layered ones? Yes for normal declarations: styles outside any layer win over every layer. For !important declarations the order reverses, so the earliest layer's important rule wins.
  • Why is !important a code smell, and when is it fine? It escapes the normal cascade and invites more !important to override it. It is reasonable in utility classes that must always apply and in user stylesheets for accessibility.
  • How do you fight specificity creep in a large app? Keep selectors flat (single classes, as in BEM), use :where() in base styles, put third-party CSS in a low layer, and avoid IDs for styling.
@layer reset, base, components, utilities;

@layer components {
  .card .actions button.primary { background: navy; }   /* (0, 3, 1) */
}

@layer utilities {
  .btn-primary { background: teal; }                     /* (0, 1, 0), still wins */
}
Layer order declared up front. The .btn-primary utility wins over the heavier component selector because utilities is a later layer. Not rendered for this page.

Flexbox and grid

  • Flexbox or grid? Flexbox distributes items along one axis and lets content size them, good for toolbars, nav bars and rows of buttons. Grid defines rows and columns together, good for page layouts and card galleries where items should line up both ways.
  • justify-content versus align-items? justify-content works on the main axis (the flex-direction), align-items on the cross axis. Changing flex-direction to column swaps which one controls horizontal placement.
  • What does flex: 1 mean? flex-grow 1, flex-shrink 1 and flex-basis 0%, so items share free space equally regardless of their content size.
  • Why does long text overflow a flex item instead of wrapping or truncating? Flex items default to min-width: auto, which stops them from shrinking below their content's width. Setting min-width: 0 on the item fixes it, and it is one of the most common real-world CSS bugs.
  • What is gap, and why prefer it to margins? gap sets spacing between flex or grid items only, with no extra space on the outer edges and no need for last-child overrides.
  • auto-fit versus auto-fill in repeat()? Both create as many tracks as fit. auto-fill keeps empty tracks; auto-fit collapses them so existing items stretch to fill the row.
  • What is the fr unit? A fraction of the free space in the grid container after fixed and content-sized tracks are placed.
  • What are grid-template-areas good for? Naming regions (header, sidebar, main, footer) so a layout is readable and can be rearranged in a media query by redefining the areas.
  • What is subgrid? A nested grid that uses its parent's tracks, so content inside separate cards (titles, prices, buttons) lines up across the row.
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
  gap: 1.5rem;
}

.row {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

.row .title {
  flex: 1;
  min-width: 0;              /* allow shrinking below the text width */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
A responsive card grid with no media queries, and the flex overflow fix. Not rendered for this page.

Positioning and stacking contexts

Positioning questions and the z-index puzzle
QuestionWhat it testsWhat a strong answer shows
relative, absolute, fixed, sticky: how does each position?Positioningrelative offsets the box from where it would be and keeps its space; absolute is placed against the nearest positioned ancestor and leaves the flow; fixed is placed against the viewport; sticky behaves as relative until a scroll threshold, then sticks within its container.
Why does position: sticky not stick?Sticky debuggingNo top (or other inset) value, an ancestor with overflow hidden, auto or scroll becoming the scroll container, or a parent that is no taller than the sticky element.
Why is a position: fixed element scrolling with its parent?Containing blocksAn ancestor has transform, filter or perspective (and some other properties), which makes that ancestor the containing block for fixed descendants.
What is a stacking context?Layering modelA group of elements layered together and then placed as one unit in its parent context. z-index values only compare within the same context.
What creates a stacking context?TriggersThe root, positioned elements with a z-index other than auto, flex and grid children with a z-index, opacity below 1, transform, filter, mix-blend-mode, isolation: isolate, and will-change on those properties, among others.
A dropdown with z-index: 9999 is hidden behind a header with z-index: 10. Why?Applied debuggingThe dropdown lives inside a parent that formed its own stacking context with a lower level, such as a transformed card. Its 9999 only competes inside that parent. Fix the parent's context or render the dropdown at a higher level in the DOM.
Positioning questions and the z-index puzzle. Scroll sideways on a small screen.

Responsive design and container queries

  • Mobile-first or desktop-first media queries? Mobile-first writes base styles for small screens and adds min-width queries as space grows, which usually means less overriding.
  • What are container queries? Styles based on the size of a component's container instead of the viewport. Mark an ancestor with container-type: inline-size, then use @container rules, so the same card can be compact in a sidebar and wide in the main column.
  • What are container query units? Units such as cqi and cqw that size things relative to the query container, useful for type inside a resizable component.
  • Which media features beyond width matter? prefers-reduced-motion to tone down animation, prefers-color-scheme for dark mode, hover and pointer to adapt for touch, and print styles.
  • What does :has() add? A relational selector that styles an element based on its descendants or siblings, such as a form field wrapper that turns red when its input is invalid, without JavaScript.
  • What are logical properties? margin-inline, padding-block, inset-inline-start and similar properties that follow writing direction, so a layout works in right-to-left languages without a separate stylesheet.
  • Why can 100vh cause problems on phones? Mobile browser toolbars change the visible height. The newer dvh, svh and lvh units describe the dynamic, small and large viewport heights.
.card-slot {
  container-type: inline-size;
}

.card {
  display: grid;
  gap: 1rem;
}

@container (min-width: 32rem) {
  .card {
    grid-template-columns: 12rem 1fr;
  }
}

@media (prefers-reduced-motion: reduce) {
  .card { transition: none; }
}
A card that switches to a horizontal layout when its container, not the screen, is wide enough. Not rendered for this page.

Rendering performance and architecture

Senior CSS questions
QuestionWhat it testsWhat a strong answer shows
Layout, paint and composite: what triggers each?Rendering pipelineChanging geometry (width, top, font size) triggers layout, then paint. Changing color or shadows triggers paint. Changing transform or opacity can often be handled by the compositor alone, which is why they animate smoothly.
How do you animate a panel sliding in without jank?Animation performanceAnimate transform: translateX and opacity, not left or width. Use will-change sparingly and only while the animation runs, since each promoted layer costs memory.
What does content-visibility: auto do?Rendering workIt lets the browser skip layout and paint for off-screen sections until they approach the viewport. Pair it with contain-intrinsic-size to avoid scrollbar jumps.
Why is CSS render-blocking, and what do you do about it?LoadingThe browser waits for stylesheets before first paint to avoid a flash of unstyled content. Keep critical CSS small, inline it if it helps, and load the rest without blocking.
How do web fonts cause layout shift, and how do you limit it?FontsSwapping a fallback for the web font changes text size. font-display, preloading the main font, and fallback metric adjustments such as size-adjust reduce the jump.
BEM, CSS Modules, utility classes or CSS-in-JS?ArchitectureBEM gives naming discipline in global CSS; CSS Modules scope class names at build time; utility-first frameworks trade long class lists for consistency; runtime CSS-in-JS adds JavaScript cost. Pick by team size and rendering model, and say the trade-off.
Senior CSS questions. Scroll sideways on a small screen.

Fictional example

Answering "Our modal appears under the sticky header. Fix it."
Interviewer
The modal has position fixed and z-index 1000. The sticky header has z-index 50. Yet the header covers the top of the modal. Where do you look?
Candidate
A higher z-index losing means the two are not in the same stacking context. I would inspect the modal's ancestors in dev tools for anything that creates a context: a transform, a filter, opacity below one, or a z-index on a positioned parent. A common culprit is a page wrapper with a transform for a slide-in animation. That wrapper becomes a stacking context, and if it sits at a lower level than the header, everything inside it, even at 1000, stays under the header. The transform also makes the wrapper the containing block for the fixed modal, which explains if the modal scrolls with the page too. The robust fix is to render the modal at the end of body, through a portal in React for example, or with the native dialog element's top layer. Then I would define a small z-index scale as custom properties so these values stop being guesses.

One-week CSS practice plan

  • Day 1: write ten selector pairs and predict which wins before checking in dev tools; include :is(), :where(), !important and a layered rule.
  • Day 2: rebuild a navigation bar and a pricing row with flexbox, then break them with long text and fix the overflow.
  • Day 3: build a page layout with grid-template-areas and a card gallery with auto-fit, then rearrange both for mobile.
  • Day 4: reproduce the hidden dropdown and the non-sticky header on purpose, and explain each in one sentence.
  • Day 5: convert a component to container queries and add reduced-motion and dark mode support.
  • Days 6 and 7: profile an animation in the browser's performance panel, move it to transform and opacity, and practice recreating a design from a screenshot within 30 minutes.

Markup questions such as semantics, forms and accessibility are on the HTML interview questions page. For the whole frontend loop, including JavaScript and framework rounds, see frontend developer interview questions.

CSS answers are easy to get half right out loud. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of your mock frontend round on your computer, so afterwards you can check whether you explained the stacking context or only named the fix. In practice it can read a layout screenshot or a block of CSS and suggest an approach, and with Pro or the free trial it can use the résumé and job description you add. The transcript and notes stay for later review.

Questions people ask

What CSS questions are asked in interviews?

Expect the box model and box-sizing, specificity and the cascade, cascade layers, flexbox versus grid, positioning, stacking contexts and z-index bugs, responsive design with media and container queries, and animation performance.

How is CSS specificity calculated?

Count IDs, then classes, attributes and pseudo-classes, then elements and pseudo-elements, and compare those three numbers from the left. Inline styles and !important sit outside this count, and :where() contributes zero.

When should I use flexbox and when grid?

Use flexbox to distribute items along one axis where content decides sizes, such as toolbars and button rows. Use grid when you need rows and columns aligned together, such as page layouts and card galleries.

Why is my z-index not working?

Either the element is not positioned or a flex or grid item, or it sits inside a different stacking context created by an ancestor with transform, opacity, filter or its own z-index. z-index only competes within the same context.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP