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
- Cascade order: origin & importance → inline (element-attached) →
@layer→ specificity → source order. Specificity is only a tie-breaker inside the same origin and layer. - 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. - Inherited by default: text properties (
color,font-*,line-height,visibility). Not inherited: box properties (margin,padding,border,background,width). Useinherit,initial,unsetorrevertto override. box-sizing: border-boxmakeswidthinclude padding and border. Set it globally with*, *::before, *::after { box-sizing: border-box; }.- 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. absoluteis placed against the nearest positioned ancestor.fixeduses the viewport unless an ancestor hastransform/filter.stickyneeds atopvalue and breaks inside anoverflow: hiddenancestor.z-indexonly compares elements inside the same stacking context.opacity < 1,transform,filter,isolation: isolateand positioned +z-indexall create one.- Flexbox is one-dimensional (content decides size); Grid is two-dimensional (the container defines tracks).
flex: 1means1 1 0%. - Add
min-width: 0to a flex item (or useminmax(0, 1fr)in grid) when long content overflows; the defaultmin-width: autostops items from shrinking below their content. repeat(auto-fit, minmax(240px, 1fr))gives a responsive card grid without media queries.auto-fillkeeps empty tracks;auto-fitcollapses them so items stretch.emis relative to the element's font size (the parent's forfont-sizeitself);remto the root. Useremfor type and spacing,%/frfor layout,dvhinstead of100vhon mobile.clamp(min, preferred, max)gives fluid type and spacing:font-size: clamp(1rem, 0.5rem + 2vw, 2rem).- 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. - Responsive images:
srcset+sizeslet the browser pick a resolution;<picture>is for art direction and formats. Always setwidth/height(oraspect-ratio) to avoid layout shift. - Animate only
transformandopacityfor smooth 60fps; they skip layout and paint. Respectprefers-reduced-motion. - 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!importantin 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 withinitial,unset(inherit if inheritable, else initial) orrevert(back to the browser default).
Interview questions
- How does the browser decide which CSS rule applies?
- How is specificity calculated?
- Difference between
initial,inherit,unsetandrevert?
!important & cascade layers (@layer)
@layer lets you order groups of styles so a later layer wins regardless of selector specificity.
!importantmoves a declaration into a higher-priority group. Two!importantrules 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
!importantthe order flips: earlier layers win, and layered!importantbeats 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
!importantacceptable? - What problem do cascade layers solve?
- If unlayered CSS beats layered CSS, why does layered
!importantwin?
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):widthis the content only, so padding and border are added on top.border-box:widthincludes 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. outlineandbox-shadowdo not take up space, so they never shift layout.
Interview questions
- Explain the CSS box model.
- Difference between
content-boxandborder-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;
widthandheightare 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/gridmake the element block-level and switch its children to flex/grid layout;inline-flex/inline-griddo the same but stay inline. Modern two-value syntax:display: inline flex.display: contentsremoves the element's own box so its children act as children of the grandparent.display: flow-rootcreates a new block formatting context.
Interview questions
- Difference between
display: none,visibility: hiddenandopacity: 0? - Difference between
inline,blockandinline-block? - Why is there a small gap between
inline-blockelements?
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:overflowother thanvisible/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-topis 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 andz-indexhave no effect (except on flex/grid items forz-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 withtransform,filter,perspective,contain: paintor matchingwill-changebecomes its containing block instead.sticky: acts likerelativeuntil its scroll container scrolls it to the threshold (top: 0), then sticks until its parent scrolls away.inset: 0is the shorthand fortop/right/bottom/left: 0.
Interview questions
- Difference between
relative,absoluteandfixed? - How does
position: stickywork and why might it not stick? - My
position: fixedelement 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-indexapplies 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-indexnotauto;fixed/sticky; flex/grid item withz-index;opacity < 1;transform,filter,backdrop-filter,perspective,clip-path,mask;mix-blend-mode;isolation: isolate;will-changeon 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 withshowModal(), popovers, fullscreen) sits above every stacking context, so noz-indexis needed.
Interview questions
- Why does my element with
z-index: 9999appear below another withz-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: autowith a width. Inline content:text-align: centeron the parent. - Both axes, one child:
display: grid; place-items: center;(shortest) or flex withjustify-content+align-items. - Overlay centering:
position: absolute; inset: 0; margin: auto;with a known size, ortop: 50%; left: 50%; transform: translate(-50%, -50%)for unknown sizes. - Sticky footer: make the page a column (
min-height: 100dvh) and letmaingrow (flex: 1orgrid-template-rows: auto 1fr auto). - Holy grail: header, footer, a main column and two sidebars. Grid with
grid-template-areasis 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-contentaligns on the main axis,align-itemson 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), default0 1 auto.flex-wrap: wrapallows multiple lines; thenalign-contentdistributes the lines.gapspaces items without margin hacks.- Flex items have
min-width: auto, so they will not shrink below their content. Long words orpreblocks overflow until you setmin-width: 0(oroverflow: hidden). align-selfoverrides alignment for one item;orderchanges 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-shrinkandflex-basis. - What does
flex: 1mean and how is it different fromflex: auto? - A flex item with a long URL overflows its container. Why and how do you fix it?
- Difference between
align-itemsandalign-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. Thefrunit 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 / -1spans the full width,span 2spans 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-rowsand control flow withgrid-auto-flow(row,column,dense). 1fris reallyminmax(auto, 1fr), so long content can still blow out a column. Useminmax(0, 1fr)to allow shrinking.- Alignment:
justify-items/align-itemsalign items in their cells (place-itemssets both);justify-content/align-contentalign the whole grid in the container.
Interview questions
- What is the
frunit? - Difference between
auto-fillandauto-fit? - What is the difference between the explicit and implicit grid?
- Why does my
1frcolumn 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 andorder, 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 ownfont-size(forfont-sizeitself, 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 forwidth/font-size; for padding and margin it is the containing block's width; fortransform: translate()it is the element's own size.vw/vh: 1% of the viewport. On mobile100vhignores the collapsing URL bar. Usesvh(smallest),lvh(largest) ordvh(dynamic, changes as bars show and hide).ch: width of the0glyph, great for readable line length (max-width: 65ch). Container unitscqi/cqwfollow a query container.clamp(min, preferred, max)=max(min, min(preferred, max)). Combine withvworcqifor fluid type that never gets too small or too large.
Interview questions
- Difference between
emandrem? - Why is
100vha 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) orsize(both axes, needs an explicit height). - Optionally name it:
container-name: cardor the shorthandcontainer: 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. Usecqiwithclamp()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-typefirst? - 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:
srcsetlists files with width descriptors (800w);sizestells 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
widthandheightattributes (or CSSaspect-ratio) so the browser reserves space and avoids CLS.object-fit: covercrops 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
srcsetandsizeswork together? - When would you use
<picture>instead of justsrcset? - 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/::afterneedcontent(even'') and do not work on replaced elements likeimgorinput. Text incontentis 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-visibleshows 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
::beforework 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. Settransition: 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,topormarginre-runs layout;colororbackgroundre-runs paint;transformandopacitycan run on the compositor only. will-change: transformhints the browser to promote a layer ahead of time. Use it sparingly and only just before an animation; every layer costs GPU memory.displaywas not animatable. Modern browsers supporttransition-behavior: allow-discretewith@starting-styleto animate elements in and out ofdisplay: 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-changedo 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 withvar(--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 withgetComputedStyle(el).getPropertyValue('--x'). - They cannot be used inside media query conditions or selectors, only in property values.
@propertyregisters 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: subgridlets 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-startinstead ofmargin-left,padding-block,inset-inline-end,inline-sizeinstead ofwidth. They make RTL and vertical text work automatically. - Also worth knowing:
aspect-ratio,gapin 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?