PrepStack › Frontend › CSS & Responsive Design

CSS & Responsive Design interview cheat sheet

Cascade, box model, Flexbox vs Grid, positioning, units and responsive layouts

CSS rounds test whether you can explain why a style wins or loses and build a layout without trial and error. Expect questions on specificity and the cascade, the box model, positioning and z-index, Flexbox vs Grid, units, and mobile-first responsive design, plus a live task such as centering a div or building a card grid. Read the 15-minute revision first, then use Quiz mode and answer out loud. The CSS snippets are illustrations; the small JS snippets that model CSS rules are executed and verified.

15-minute revision

  1. Cascade order: origin & importance → inline (element-attached) → @layer → specificity → source order. Specificity is only a tie-breaker inside the same origin and layer.
  2. Specificity is a triple (IDs, classes/attributes/pseudo-classes, types/pseudo-elements). * and combinators add 0, :where() adds 0, and :is()/:not()/:has() take their most specific argument.
  3. Inherited by default: text properties (color, font-*, line-height, visibility). Not inherited: box properties (margin, padding, border, background, width). Use inherit, initial, unset or revert to override.
  4. box-sizing: border-box makes width include padding and border. Set it globally with *, *::before, *::after { box-sizing: border-box; }.
  5. Vertical margins of block boxes in normal flow collapse to the largest one. Flex/grid items, floats, absolute boxes and a parent with padding, border or a new BFC (display: flow-root) stop it.
  6. absolute is placed against the nearest positioned ancestor. fixed uses the viewport unless an ancestor has transform/filter. sticky needs a top value and breaks inside an overflow: hidden ancestor.
  7. z-index only compares elements inside the same stacking context. opacity < 1, transform, filter, isolation: isolate and positioned + z-index all create one.
  8. Flexbox is one-dimensional (content decides size); Grid is two-dimensional (the container defines tracks). flex: 1 means 1 1 0%.
  9. Add min-width: 0 to a flex item (or use minmax(0, 1fr) in grid) when long content overflows; the default min-width: auto stops items from shrinking below their content.
  10. repeat(auto-fit, minmax(240px, 1fr)) gives a responsive card grid without media queries. auto-fill keeps empty tracks; auto-fit collapses them so items stretch.
  11. em is relative to the element's font size (the parent's for font-size itself); rem to the root. Use rem for type and spacing, %/fr for layout, dvh instead of 100vh on mobile.
  12. clamp(min, preferred, max) gives fluid type and spacing: font-size: clamp(1rem, 0.5rem + 2vw, 2rem).
  13. Mobile-first means base styles for small screens, then @media (min-width: …) to add. Container queries (container-type: inline-size + @container) respond to the parent's size instead of the viewport.
  14. Responsive images: srcset + sizes let the browser pick a resolution; <picture> is for art direction and formats. Always set width/height (or aspect-ratio) to avoid layout shift.
  15. Animate only transform and opacity for smooth 60fps; they skip layout and paint. Respect prefers-reduced-motion.
  16. Custom properties (--gap) are inherited, live at runtime and can change in media queries or from JS. Sass variables are compiled away.

Cascade & the Box Model

Cascade, specificity & inheritance

When rules conflict, the browser checks origin and importance, then layers, then specificity, then source order.

  • The cascade is the algorithm that picks one winning value for every property on every element.
  • Specificity is compared column by column: (IDs, classes + attributes + pseudo-classes, types + pseudo-elements). One ID beats any number of classes.
  • *, combinators (>, +, ~, space) and :where() add nothing. :is(), :not() and :has() count as their most specific argument.
  • Inline style="" attributes beat any selector in the author stylesheet. A normal declaration marked !important in a stylesheet beats an inline normal style.
  • Inheritance only applies when no rule sets the property. Text-related properties inherit; box-related ones do not. Force it with inherit, reset with initial, unset (inherit if inheritable, else initial) or revert (back to the browser default).

Interview questions

  • How does the browser decide which CSS rule applies?
  • How is specificity calculated?
  • Difference between initial, inherit, unset and revert?

!important & cascade layers (@layer)

@layer lets you order groups of styles so a later layer wins regardless of selector specificity.

  • !important moves a declaration into a higher-priority group. Two !important rules then fall back to the normal tie-breakers (layers, specificity, order).
  • @layer reset, base, components, utilities; declares the order up front. Later layers win for normal declarations, even with lower specificity.
  • Unlayered styles beat all layered styles for normal declarations. This makes it easy to put third-party CSS in a layer and override it simply.
  • For !important the order flips: earlier layers win, and layered !important beats unlayered !important. This lets a reset layer protect critical rules.
  • Import a file into a layer with @import url("lib.css") layer(vendor);. Layers can nest (framework.layout). Supported in all major browsers since 2022.

Interview questions

  • When is !important acceptable?
  • What problem do cascade layers solve?
  • If unlayered CSS beats layered CSS, why does layered !important win?

Box model & box-sizing

Every element is a box of content, padding, border and margin; box-sizing decides what width measures.

  • From inside out: content → padding → border → margin. Background paints under content, padding and border, not margin.
  • content-box (default): width is the content only, so padding and border are added on top.
  • border-box: width includes padding and border, so the box is exactly the size you set. This is what most resets use.
  • Margins can be negative and auto. Padding cannot be negative. Percent padding and margin (even top/bottom) are relative to the containing block's width.
  • outline and box-shadow do not take up space, so they never shift layout.

Interview questions

  • Explain the CSS box model.
  • Difference between content-box and border-box?
  • Difference between padding and margin?

Display types & hiding elements

display sets how a box behaves outside (block or inline) and how it lays out its children (flow, flex, grid).

  • block: starts on a new line, fills the available width, respects width, height and all margins (div, p, section).
  • inline: flows in the line of text; width and height are ignored and vertical margins do not push lines apart (span, a, strong).
  • inline-block: sits inline but accepts width, height and vertical margins. Watch the whitespace gap between inline-block siblings.
  • flex/grid make the element block-level and switch its children to flex/grid layout; inline-flex/inline-grid do the same but stay inline. Modern two-value syntax: display: inline flex.
  • display: contents removes the element's own box so its children act as children of the grandparent. display: flow-root creates a new block formatting context.

Interview questions

  • Difference between display: none, visibility: hidden and opacity: 0?
  • Difference between inline, block and inline-block?
  • Why is there a small gap between inline-block elements?

Margin collapse & block formatting context

Adjacent vertical margins in normal block flow merge into one; a new BFC isolates a box from that and from floats.

  • Margin collapse happens only for vertical margins of block-level boxes in normal flow. Horizontal margins never collapse.
  • Three cases: adjacent siblings; parent and first/last child with no border, padding, inline content or height between them; and an empty block whose top and bottom margins touch.
  • Result: both positive → the larger wins; mixed signs → they are added; both negative → the most negative.
  • No collapse for flex and grid items, floats, absolutely positioned boxes, inline-blocks, or a parent that creates a new BFC (for its children).
  • A block formatting context is a mini layout region. It contains its floats (no collapsing height), does not overlap outside floats, and stops parent/child margin collapse.
  • Create a BFC with display: flow-root (purpose-built, no side effects). Others: overflow other than visible/clip, floats, position: absolute/fixed, inline-block, table cells, contain: layout, flex and grid items.

Interview questions

  • What is margin collapsing?
  • My child's margin-top is pushing the parent down instead of creating space inside it. Why and how do you fix it?
  • What is a Block Formatting Context and why should I care?

Positioning & Stacking

Positioning: static, relative, absolute, fixed, sticky

position decides whether a box stays in flow and what its top/left/right/bottom offsets are measured from.

  • static (default): normal flow; offsets and z-index have no effect (except on flex/grid items for z-index).
  • relative: stays in flow and keeps its space; offsets just nudge it visually. Main use: becoming the containing block for absolute children.
  • absolute: removed from flow; placed against the nearest ancestor that is positioned (not static), or the initial containing block if none.
  • fixed: removed from flow; placed against the viewport and does not scroll. Gotcha: an ancestor with transform, filter, perspective, contain: paint or matching will-change becomes its containing block instead.
  • sticky: acts like relative until its scroll container scrolls it to the threshold (top: 0), then sticks until its parent scrolls away.
  • inset: 0 is the shorthand for top/right/bottom/left: 0.

Interview questions

  • Difference between relative, absolute and fixed?
  • How does position: sticky work and why might it not stick?
  • My position: fixed element scrolls with the page. Why?

Stacking context & z-index

z-index only orders siblings inside the same stacking context; a child can never escape its parent's context.

  • z-index applies to positioned elements (not static) and to flex/grid items.
  • A stacking context is a group that is painted as one unit. Children are ordered only against each other, then the whole group is placed in its parent context.
  • Created by: the root; positioned element with z-index not auto; fixed/sticky; flex/grid item with z-index; opacity < 1; transform, filter, backdrop-filter, perspective, clip-path, mask; mix-blend-mode; isolation: isolate; will-change on those; contain: layout/paint; container-type: size/inline-size; top-layer elements.
  • Paint order inside a context: background and borders → negative z-index → block boxes in flow → floats → inline content → z-index: 0/auto positioned → positive z-index.
  • The top layer (<dialog> opened with showModal(), popovers, fullscreen) sits above every stacking context, so no z-index is needed.

Interview questions

  • Why does my element with z-index: 9999 appear below another with z-index: 2?
  • What creates a stacking context?
  • How would you design z-index handling in a large app?

Centering & classic interview layouts

Use flex or grid for centering; know the holy grail, sticky footer, sidebar and card grid by heart.

  • Horizontal centering of a block: margin-inline: auto with a width. Inline content: text-align: center on the parent.
  • Both axes, one child: display: grid; place-items: center; (shortest) or flex with justify-content + align-items.
  • Overlay centering: position: absolute; inset: 0; margin: auto; with a known size, or top: 50%; left: 50%; transform: translate(-50%, -50%) for unknown sizes.
  • Sticky footer: make the page a column (min-height: 100dvh) and let main grow (flex: 1 or grid-template-rows: auto 1fr auto).
  • Holy grail: header, footer, a main column and two sidebars. Grid with grid-template-areas is the cleanest and collapses to one column in a media query.
  • Equal-height columns come free with flex and grid because items stretch by default (align-items: stretch).

Interview questions

  • How do you center a div horizontally and vertically?
  • How do you build a sticky footer?
  • Build a responsive card grid with no media queries.

Flexbox & Grid

Flexbox deep dive

Flexbox lays items out along one axis and shares free space with flex-grow, flex-shrink and flex-basis.

  • The main axis follows flex-direction (row by default); the cross axis is perpendicular. justify-content aligns on the main axis, align-items on the cross axis.
  • flex: <grow> <shrink> <basis>. Common values: flex: 1 = 1 1 0% (equal shares), flex: auto = 1 1 auto (share after content size), flex: none = 0 0 auto (rigid), default 0 1 auto.
  • flex-wrap: wrap allows multiple lines; then align-content distributes the lines. gap spaces items without margin hacks.
  • Flex items have min-width: auto, so they will not shrink below their content. Long words or pre blocks overflow until you set min-width: 0 (or overflow: hidden).
  • align-self overrides alignment for one item; order changes visual order only, not tab or reading order.
  • Auto margins in a flex container absorb free space, which is handy for “push to the end” patterns.

Interview questions

  • Explain flex-grow, flex-shrink and flex-basis.
  • What does flex: 1 mean and how is it different from flex: auto?
  • A flex item with a long URL overflows its container. Why and how do you fix it?
  • Difference between align-items and align-content?

CSS Grid deep dive

Grid defines rows and columns on the container and places items into cells, lines or named areas.

  • Define tracks with grid-template-columns / grid-template-rows. The fr unit shares the leftover space after fixed tracks and gaps.
  • repeat(auto-fit, minmax(200px, 1fr)) makes as many columns as fit. auto-fill keeps empty tracks; auto-fit collapses empty tracks so existing items stretch to fill the row.
  • Place items by lines (grid-column: 1 / -1 spans the full width, span 2 spans two tracks) or by named areas (grid-template-areas + grid-area).
  • Items placed beyond the defined tracks create the implicit grid; size those tracks with grid-auto-rows and control flow with grid-auto-flow (row, column, dense).
  • 1fr is really minmax(auto, 1fr), so long content can still blow out a column. Use minmax(0, 1fr) to allow shrinking.
  • Alignment: justify-items/align-items align items in their cells (place-items sets both); justify-content/align-content align the whole grid in the container.

Interview questions

  • What is the fr unit?
  • Difference between auto-fill and auto-fit?
  • What is the difference between the explicit and implicit grid?
  • Why does my 1fr column grow wider than the others?

Flexbox vs Grid: when to use which

Flexbox is content-out and one-dimensional; Grid is layout-in and two-dimensional. Real pages use both.

  • Flexbox: items decide their sizes, and the container shares leftover space along one axis. Best for nav bars, toolbars, button groups, centering, and components with unknown item counts.
  • Grid: the container defines rows and columns and items snap into them. Best for page layouts, card galleries, dashboards, forms with aligned labels, and overlapping items.
  • Wrapped flex rows do not line up with each other in columns; grid columns always align. That is the quickest way to pick.
  • Grid can overlap items by placing them in the same cells, without absolute positioning.
  • Both support gap, alignment properties and order, and both stop margin collapse.

Interview questions

  • When would you use Flexbox over Grid?
  • When is Grid the better choice?
  • Can you replace Flexbox entirely with Grid?

Responsive Design

Units: px, em, rem, %, viewport units, ch & clamp()

Pick units by what the value should follow: the root font, the parent, the container, the viewport, or nothing.

  • px: absolute CSS pixel (not a device pixel). Fine for borders and shadows; avoid for font sizes because it ignores the user's browser font setting.
  • em: relative to the element's own font-size (for font-size itself, the parent's). It compounds in nested elements. rem: relative to the root (html) font size, so it does not compound.
  • %: relative to the parent for width/font-size; for padding and margin it is the containing block's width; for transform: translate() it is the element's own size.
  • vw/vh: 1% of the viewport. On mobile 100vh ignores the collapsing URL bar. Use svh (smallest), lvh (largest) or dvh (dynamic, changes as bars show and hide).
  • ch: width of the 0 glyph, great for readable line length (max-width: 65ch). Container units cqi/cqw follow a query container.
  • clamp(min, preferred, max) = max(min, min(preferred, max)). Combine with vw or cqi for fluid type that never gets too small or too large.

Interview questions

  • Difference between em and rem?
  • Why is 100vh a problem on mobile and what replaces it?
  • How do you make font sizes fluid?

Responsive design & mobile-first media queries

Start with a single-column mobile layout and add complexity with min-width media queries at content-driven breakpoints.

  • Responsive design = fluid layouts + flexible media + media queries. Add <meta name="viewport" content="width=device-width, initial-scale=1"> or mobile browsers render a 980px desktop page zoomed out.
  • Mobile-first: base CSS targets small screens; @media (min-width: …) layers on enhancements. Small devices download less override CSS and the simplest layout is the default.
  • Choose breakpoints where the content breaks, not by device models. A few (around 40em, 64em, 80em) are usually enough.
  • Modern range syntax: @media (width >= 48em) and (30em <= width < 60em). Supported in all modern browsers.
  • Media features beyond width: prefers-color-scheme, prefers-reduced-motion, prefers-contrast, hover, pointer: coarse, orientation, print.
  • Use intrinsic layout (flex-wrap, auto-fit, clamp) first; many components then need no media query at all.

Interview questions

  • What is mobile-first design and why use it?
  • How do you choose breakpoints?
  • What does the viewport meta tag do?
  • How do you handle hover on touch devices?

Container queries

@container styles a component by the size of its container, so the same card works in a sidebar and in a wide grid.

  • Mark an ancestor as a query container: container-type: inline-size (width only, the usual choice) or size (both axes, needs an explicit height).
  • Optionally name it: container-name: card or the shorthand container: card / inline-size. Queries then target the nearest container with that name.
  • Query with @container (width > 30rem) { … } or @container card (min-width: 30rem) { … }. An element cannot query itself, only an ancestor.
  • Container units: cqw, cqh, cqi (inline), cqb (block), cqmin, cqmax. Use cqi with clamp() for type that scales with the component.
  • Style queries (@container style(--theme: dark)) test custom property values; support is still uneven (Chromium and Safari), so treat them as an enhancement.
  • Size containers are supported in all modern browsers since 2023. A size container also creates a new stacking context and applies containment.

Interview questions

  • Difference between media queries and container queries?
  • Why do you need container-type first?
  • Why can't an element query its own size?

Responsive images & media

Let the browser choose the best file with srcset and sizes, use <picture> for art direction and formats, and reserve space to avoid layout shift.

  • img { max-width: 100%; height: auto; } is the base rule for fluid images.
  • Resolution switching: srcset lists files with width descriptors (800w); sizes tells the browser how wide the image will be displayed. The browser picks the best file for screen size and pixel density.
  • For fixed-size images (logos, avatars) use x-descriptors: srcset="a.png 1x, a@2x.png 2x".
  • Art direction (different crop per breakpoint) and format fallback (AVIF → WebP → JPEG) use <picture> with <source media> or <source type>.
  • Set width and height attributes (or CSS aspect-ratio) so the browser reserves space and avoids CLS. object-fit: cover crops without distortion.
  • loading="lazy" for below-the-fold images; never lazy-load the LCP hero image. fetchpriority="high" can boost it.

Interview questions

  • How do srcset and sizes work together?
  • When would you use <picture> instead of just srcset?
  • How do you prevent layout shift from images?

Selectors, Motion & Modern CSS

Pseudo-classes vs pseudo-elements, :is, :where, :has

Pseudo-classes (:hover) select elements in a state; pseudo-elements (::before) style a part of an element or create a virtual box.

  • Pseudo-class (one colon): matches an existing element by state or position: :hover, :focus-visible, :checked, :nth-child(2n), :first-of-type, :not(), :empty.
  • Pseudo-element (two colons): targets part of an element or generates one: ::before, ::after, ::first-line, ::placeholder, ::marker, ::selection, ::backdrop.
  • ::before/::after need content (even '') and do not work on replaced elements like img or input. Text in content is not reliable for screen readers.
  • :is(a, b) groups selectors and takes the highest specificity in the list; :where(a, b) does the same with zero specificity (great for resets and libraries).
  • :has() is the “parent selector”: .card:has(img) styles a card that contains an image; label:has(+ input:invalid) looks at a following sibling. Supported in all modern browsers.
  • :nth-child(2 of .item) counts only matching siblings. :focus-visible shows focus rings for keyboard users but not mouse clicks.

Interview questions

  • Difference between a pseudo-class and a pseudo-element?
  • Difference between :is() and :where()?
  • What is :has() and what can it do that was impossible before?
  • Why doesn't ::before work on an <img> or <input>?

Transitions vs animations & performance

Transitions animate between two states when a value changes; @keyframes animations run multi-step sequences on their own. Animate transform and opacity for speed.

  • Transition: needs a trigger (class change, :hover) and goes from the old value to the new value. Set transition: transform 200ms ease-out; on the base state.
  • Animation: defined with @keyframes, can autoplay, loop (infinite), alternate, pause (animation-play-state) and keep its end state (animation-fill-mode: forwards).
  • Rendering pipeline: Style → Layout → Paint → Composite. Changing width, top or margin re-runs layout; color or background re-runs paint; transform and opacity can run on the compositor only.
  • will-change: transform hints the browser to promote a layer ahead of time. Use it sparingly and only just before an animation; every layer costs GPU memory.
  • display was not animatable. Modern browsers support transition-behavior: allow-discrete with @starting-style to animate elements in and out of display: none.
  • Always respect @media (prefers-reduced-motion: reduce).

Interview questions

  • Difference between CSS transitions and animations?
  • Which properties are cheap to animate and why?
  • What does will-change do and what is the risk?
  • How would you make a smooth slide-in sidebar?

CSS custom properties (variables)

Custom properties are inherited, runtime values you can change per element, per media query or from JavaScript.

  • Declare with a -- name (--brand: #2563eb;) and read with var(--brand, fallback). Names are case-sensitive.
  • They cascade and inherit like normal properties, so you can override them on a subtree: .dark { --bg: #111; }.
  • They are resolved at computed-value time. If the substituted value is invalid for the property, the property behaves as unset (not as the previous valid rule).
  • Change them from JS with el.style.setProperty('--x', '10px') and read with getComputedStyle(el).getPropertyValue('--x').
  • They cannot be used inside media query conditions or selectors, only in property values.
  • @property registers a typed property (syntax: '<color>', inherits, initial-value), which makes it animatable and validated.

Interview questions

  • Difference between CSS variables and Sass variables?
  • How would you implement dark mode?
  • What happens if a variable holds an invalid value for the property?

Modern CSS: nesting, subgrid, logical properties

Native nesting, subgrid, logical properties and newer functions remove much of what preprocessors and JS used to do.

  • Native nesting works in all modern browsers: .card { & h2 { … } &:hover { … } }. A nested selector acts like it is wrapped in :is(), so specificity follows :is() rules. Plain nested selectors like .card { h2 { } } are allowed too.
  • Subgrid: grid-template-columns: subgrid lets a nested grid reuse its parent's tracks, so card titles, bodies and footers line up across cards.
  • Logical properties follow writing direction: margin-inline-start instead of margin-left, padding-block, inset-inline-end, inline-size instead of width. They make RTL and vertical text work automatically.
  • Also worth knowing: aspect-ratio, gap in flexbox, min()/max()/clamp(), accent-color, color-mix(), text-wrap: balance, :focus-visible, @supports, the <dialog> element and the Popover API.
  • Use @supports (selector(:has(*))) or @supports (display: grid) for feature detection and progressive enhancement.

Interview questions

  • What is subgrid and what problem does it solve?
  • Why use logical properties?
  • How is native CSS nesting different from Sass nesting?
  • How do you use new CSS features safely?

CSS architecture: BEM, CSS Modules, CSS-in-JS, Tailwind

Every approach fights the same problem, global scope and specificity in a large codebase, with different trade-offs in build cost, runtime cost and DX.

  • BEM (block__element--modifier): a naming convention that keeps selectors flat (one class, low specificity) and makes ownership obvious. No tooling, but relies on discipline.
  • CSS Modules: the build tool rewrites class names to unique hashes per file, giving local scope by default. Plain CSS, zero runtime, works well with React and Next.js.
  • Runtime CSS-in-JS (styled-components, Emotion): styles live in components and can use props, but inject styles at runtime, add JS cost, and fit badly with React Server Components and streaming SSR.
  • Zero-runtime CSS-in-JS (vanilla-extract, Linaria, Panda CSS) writes styles in TS/JS but extracts static CSS at build time.
  • Tailwind (utility-first): small single-purpose classes in markup, a design-token scale, only used classes are generated, tiny CSS that stops growing. Trade-offs: long class lists, a learning curve, and markup coupled to styling.
  • Whatever you pick: design tokens in custom properties, a reset in a low layer, low and flat specificity, and co-located component styles.

Interview questions

  • What is BEM and why use it?
  • CSS Modules vs CSS-in-JS?
  • What are the pros and cons of Tailwind?
  • How would you structure CSS for a large app with many teams?