Skip to content
Tutorials Center
My learning

Topics

Lesson 139 of 139 ยท Practice and Review

CSS Interview Questions

Prepare for front-end interviews with 39 CSS questions and clear answers on the box model, specificity, flexbox, grid, responsive design, performance and architecture.

CSS questions come up in almost every front-end interview, and they are rarely about memorizing property names. Interviewers want to know whether you understand why the browser does what it does: why one rule beats another, why an element overflows, why z-index: 9999 didn't help. This page collects 39 questions you are likely to hear, grouped by level and topic, with concise answers you can check yourself against.

Each answer is hidden. Read the question, say your answer out loud (or write it down), then open it to compare. A few code-reading questions show a live example: predict the result first, then run it. Every answer links to the lesson that covers the topic in depth, so you can fill any gap you find.

Junior: fundamentals

1. What are the three ways to add CSS to a page, and which should you use?

An external stylesheet with <link rel="stylesheet">, a <style> element in the document, and the style attribute on an element. Use external stylesheets for almost everything: they are cached by the browser and shared between pages. Inline style attributes have very high priority and can't use media queries or pseudo-classes, so keep them for values set by scripts or for passing custom properties. See Adding CSS to a Page.

2. Explain the CSS box model.

Every element is rendered as a rectangular box made of four layers, from the inside out: the content, padding (space inside the border, which shows the background), the border, and margin (transparent space outside the border that separates it from neighbors). The size the element takes up in the layout is the sum of these layers. See The Box Model.

3. What is the difference between content-box and border-box?

They control what width and height measure. With the default content-box, they set the content area only, so padding and border are added on top: a 200px box with 20px padding becomes 240px wide. With border-box, they include padding and border, so the box stays 200px and the content area shrinks. Most projects set *, *::before, *::after { box-sizing: border-box; } because it makes sizes predictable. See box-sizing.

4. What is the difference between a class selector and an ID selector?

A class (.card) can be used on any number of elements, and an element can have several classes. An ID (#main) must be unique in the document. In CSS, the big difference is specificity: one ID outweighs any number of classes, which makes ID-based rules hard to override. Most style guides use classes for styling and keep IDs for fragment links, form labels and scripts. See Selector Basics.

5. What is specificity, and how is it calculated?

Specificity is the score the browser uses to choose between conflicting rules from the same origin and layer. Each selector gets three numbers: (IDs, classes + attributes + pseudo-classes, types + pseudo-elements). They are compared column by column from the left, and the first difference decides; columns never carry over, so (1, 0, 0) beats (0, 15, 0). The universal selector, combinators and :where() add nothing, and :is(), :not() and :has() take the specificity of their most specific argument. See Specificity.

6. What does "cascade" mean in Cascading Style Sheets?

The cascade is the algorithm that picks one value when several declarations target the same property on the same element. In order, it considers origin and importance (browser, user and author styles, and !important), inline styles, cascade layers, specificity, and finally the order of appearance, where the last declaration wins. See How the Cascade Works.

7. What is inheritance, and which properties inherit?

Some properties pass their computed value from parent to child when the child has no value of its own. Mostly text-related properties inherit: color, font-family, font-size, line-height, text-align, letter-spacing, visibility and cursor. Box and layout properties such as margin, padding, border, background, width and display do not. You can force either behavior with inherit or initial. See Inheritance.

8. Compare display: none, visibility: hidden and opacity: 0.
  • display: none removes the element from layout entirely; it takes no space and is hidden from screen readers.
  • visibility: hidden keeps the element's space but doesn't paint it; it can't be clicked or focused and is hidden from screen readers.
  • opacity: 0 makes it fully transparent but leaves everything else working: it takes space, can be clicked and focused, and is still read by screen readers.

To hide something visually but keep it available to screen readers, use a "visually hidden" class. See Accessible CSS.

9. What is the difference between block, inline and inline-block?

Block boxes start on a new line, stretch to fill the available width by default and respect width, height and vertical margins. Inline boxes flow within a line of text; width and height are ignored and vertical margins don't push other lines away. Inline-block boxes flow within text like inline boxes but accept width, height and all margins and padding like block boxes. See The display Property.

10. When do you use px, em, rem and %?

px is a fixed reference unit, good for borders and shadows. rem is relative to the root font size, so it respects the user's browser font setting; it's the usual choice for font sizes and spacing. em is relative to the element's own font size, useful for padding or icons that should scale with their text, but it compounds when nested. % is relative to something in the parent (the containing block's width for width and padding). See Units.

11. What is margin collapsing?

When the vertical margins of block boxes touch in normal flow, they combine into one margin the size of the larger one instead of adding up. It happens between adjacent siblings, between a parent and its first or last child when no border, padding or content separates them, and in empty blocks. It never happens with horizontal margins, or for flex items, grid items, floats or absolutely positioned elements. See Margins.

12. What is the difference between a pseudo-class and a pseudo-element?

A pseudo-class (one colon, like :hover, :focus-visible or :nth-child(2)) selects existing elements based on state or position. A pseudo-element (two colons, like ::before, ::marker or ::placeholder) styles a part of an element, or generated content, that isn't a separate element in the HTML. See Pseudo-classes and Pseudo-elements.

13. How do you center an element horizontally and vertically?

The shortest modern answer is to make the parent a grid container with display: grid; place-items: center;. With flexbox, use display: flex; justify-content: center; align-items: center;. To center a block of known width horizontally only, use margin-inline: auto. To center text inside its box, use text-align: center. See Centering Anything.

Code reading: who wins?

Predict the heading's color before you run the example.

Which color is the heading?
14. Which rule wins, and why?

Green. The scores are: #page .title (1, 1, 0); body main h1.title (0, 1, 3); .title.title.title (0, 3, 0); and :is(#page, .wrapper) h1 (1, 0, 1), because :is() takes its most specific argument, the ID. Two rules have an ID; between them, (1, 1, 0) beats (1, 0, 1) in the second column. Source order never comes into play.

Mid-level: layout

15. Flexbox or grid: how do you choose?

Flexbox lays items out in one dimension, a row or a column, and lets the content's size drive the layout; it's ideal for toolbars, nav bars, button groups and centering. Grid lays items out in two dimensions at once, with the layout defined on the container; it's ideal for page shells, card grids and anything that must line up in rows and columns. They combine well: a grid page with flex components inside. See Flexbox Basics and Grid Basics.

16. What does flex: 1 mean?

It's shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0%. The item starts from a size of zero and then takes an equal share of the free space, so several flex: 1 items end up the same width regardless of their content (as long as the content can shrink). flex: auto starts from the content size instead, so larger content gets larger items. See Flex Item Properties.

17. What is the difference between justify-content and align-items in flexbox?

justify-content distributes items along the main axis (horizontal for flex-direction: row), using values such as center or space-between. align-items positions items along the cross axis (vertical in a row). When you switch to flex-direction: column, the axes swap, so the same properties now work in the other direction. See Flex Container Properties.

18. Explain the position values.
  • static: the default; normal flow, and offsets are ignored.
  • relative: stays in the flow but can be nudged with offsets; it also becomes the containing block for absolutely positioned children.
  • absolute: removed from the flow and placed relative to the nearest positioned ancestor (or the initial containing block).
  • fixed: removed from the flow and placed relative to the viewport, so it stays put while scrolling (unless an ancestor has a transform or filter, which becomes its containing block).
  • sticky: behaves like relative until it reaches an offset such as top: 0 in its scroll container, then sticks there while its parent is visible.

See Positioning.

19. What is a stacking context, and why doesn't a huge z-index always work?

A stacking context is a group of elements that is layered as one unit within its parent context. It's created by the root element, positioned elements with a z-index other than auto, flex and grid items with a z-index, and properties such as opacity below 1, transform, filter and isolation: isolate. A child's z-index only orders it inside its own context, so a z-index: 9999 child can never rise above an element that sits above its parent's context. See z-index and Stacking Contexts.

Code reading: the stuck dropdown

The orange menu has z-index: 999, yet the blue banner covers it. Run it, then explain why.

Why is the menu underneath?
20. Why is the menu underneath, and how do you fix it?

.header has position: relative and z-index: 1, so it creates a stacking context, and the menu's 999 only counts inside it. The whole header group sits at level 1, below the banner at level 2. Fixes: raise the header's z-index above the banner's, remove the header's z-index so it doesn't form a context (if nothing else requires it), or render the menu outside the header, for example with the popover attribute, which places it in the top layer.

21. What is the difference between auto-fill and auto-fit in grid?

Both create as many tracks as fit, for example repeat(auto-fill, minmax(12rem, 1fr)). The difference shows when there are fewer items than tracks: auto-fill keeps the empty tracks, so items stay at their minimum-ish size and leave a gap at the end; auto-fit collapses the empty tracks to zero, so the 1fr maximum stretches the existing items across the row. See Grid Tracks.

22. What is the fr unit?

fr is a fraction of the free space in a grid container, after fixed tracks, gaps and content-sized tracks are taken out. grid-template-columns: 200px 1fr 2fr gives the first column 200px and splits the rest one-third and two-thirds. Note that 1fr means minmax(auto, 1fr), so a track won't shrink below its content's minimum size; use minmax(0, 1fr) to allow it. See Grid Tracks.

Code reading: the gap between paragraphs

The first paragraph has a 40px bottom margin and the second a 24px top margin. Predict the gap, then run the example: the script measures it and prints the answer in the console.

How big is the gap?
23. How tall is the gap, and how would you get 64px instead?

40px. The two vertical margins touch, so they collapse into one margin the size of the larger. To get both, put the paragraphs in a flex or grid container (display: flex; flex-direction: column; or display: grid;), where margins don't collapse, or better, drop the margins and use gap: 64px on that container. See Margins.

Mid-level: responsive design and good practice

24. What does mobile first mean, and why is it recommended?

You write the base styles for the smallest screens, then add min-width media queries that enhance the layout as space grows. Small screens get the simplest CSS without overrides to undo, the stylesheet tends to be shorter, and it pushes you to prioritize content. See Mobile-First CSS.

25. Media queries or container queries?

Media queries respond to the viewport and user preferences (width, prefers-color-scheme, prefers-reduced-motion, hover), so they suit page-level layout. Container queries respond to the size of a container element (container-type: inline-size plus @container), so a component adapts to the space it is placed in: the same card can be compact in a sidebar and wide in the main column. Modern projects use both. See Container Queries.

26. How are CSS custom properties different from Sass variables?

Sass variables are replaced with fixed values at build time and disappear from the output. Custom properties (--brand: #2563eb; used with var(--brand)) exist at runtime: they follow the cascade, inherit, can be redefined per element, inside media queries or for a theme class, and can be read and changed with JavaScript. That makes them the natural tool for theming and dark mode. See Custom Properties.

27. Why should you avoid !important, and when is it acceptable?

!important jumps a declaration over normal specificity and order, so the only way to override it is with another !important, which starts an arms race. Better tools are lowering specificity (classes, :where()), fixing source order or using cascade layers. It's acceptable for utility classes that must always apply, for user-preference overrides such as reduced motion, and for overriding third-party inline styles you can't change. See !important.

28. What is the difference between :is() and :where()?

Both match an element if it matches any selector in their list, which shortens long selector lists. :is() takes the specificity of its most specific argument; :where() always has zero specificity. Use :where() for defaults and resets that should be easy to override. See :is(), :where(), :not() and :has().

29. How do you make CSS accessible?

Keep a clearly visible focus style (style :focus-visible, never just remove outlines); keep text contrast at least 4.5:1 (3:1 for large text); don't use color alone to carry meaning; respect prefers-reduced-motion; size text in rem so user font settings work; keep visual order the same as DOM order; and hide content correctly (a visually hidden class for screen-reader-only text). See Accessible CSS.

30. What is the difference between transitions and animations?

A transition animates a property from its old value to its new value when that value changes, for example on :hover or when a class is added; it needs a trigger and has only a start and an end. A keyframe animation (@keyframes plus animation) runs on its own, can have many steps, can loop and can play in different directions. See Transitions and Keyframe Animations.

31. Why are transform and opacity preferred for animation?

After styles are calculated, the browser does layout (sizes and positions), paint (pixels) and composite (layers on screen). Animating width, top or margin triggers layout and paint on every frame, which can drop frames. transform and opacity changes can usually be handled at the composite step alone, often on the GPU, so they stay smooth. See Motion, Performance and prefers-reduced-motion.

Senior: architecture, performance and modern CSS

32. What problem do cascade layers solve?

In large codebases, specificity and file order become a fragile way to decide which styles win, especially with third-party CSS. @layer lets you declare an explicit priority order (@layer reset, base, components, utilities;) that is checked before specificity, so a simple class in utilities beats a complex selector in components. Unlayered styles beat all layers, and for !important declarations the layer order is reversed. See Cascade Layers.

Code reading: layers and !important

Layers versus !important
33. Which color wins, and why?

Red. Important declarations beat all normal declarations, so the unlayered green is out. Between important declarations, layer order is reversed: the earliest layer wins. That lets a low-level layer such as a reset protect a value that later layers must not override.

34. How would you organize CSS for a large application?

A good answer names the goals (predictable overrides, no dead code, easy deletion) and a combination of tools: design tokens as custom properties; a small reset and base layer; components styled with a naming convention like BEM, CSS Modules or @scope to avoid leaks; utility classes for one-off spacing; cascade layers to fix the order of those groups; low, flat specificity; and a linter (Stylelint) to enforce it. There's no single right system; consistency matters more than the choice. See Organizing CSS.

35. What does :has() do, and why was a parent selector considered impossible for so long?

:has() matches an element based on what comes after it in the tree, such as .card:has(img) or form:has(:user-invalid), which makes it a parent (and previous-sibling) selector. Browsers normally match selectors in a way where a change only affects the element and what follows it; :has() means a change deep in the tree can restyle an ancestor, so engines needed new invalidation work to keep it fast. It has been supported in all major browsers since late 2023.

36. How does CSS affect page load, and how do you optimize it?

CSS is render-blocking: the browser won't paint until the stylesheets in the <head> have loaded and parsed. To speed things up: ship less CSS (remove unused rules), inline small critical CSS for above-the-fold content, avoid @import chains that load files one after another, use media attributes on <link> for print or rare conditions, preload key web fonts and use font-display: swap, and give images dimensions or aspect-ratio to avoid layout shifts. See CSS Performance.

37. What is a block formatting context, and how do you create one?

A block formatting context (BFC) is an independent layout region: margins of its children don't collapse through it, it contains its floats, and it doesn't overlap neighboring floats. The cleanest way to create one is display: flow-root. Others include overflow values other than visible and clip, floats, absolute positioning, display: inline-block, and flex or grid items. The classic use was clearing floats; today it mostly fixes unexpected parent-child margin collapsing. See Floats.

38. Why use logical properties such as margin-inline-start?

Physical properties (margin-left, width) are tied to screen directions. Logical properties (margin-inline-start, inline-size, padding-block) follow the writing direction, so the same CSS works for left-to-right languages, right-to-left languages like Arabic and Hebrew, and vertical text. For an international site they remove a whole category of RTL overrides. See Writing Modes and Logical Properties.

39. How do you handle browser support for new CSS features?

Use progressive enhancement: write a solid baseline that works everywhere, then add newer features where supported. The cascade itself helps, because browsers ignore declarations they don't understand, so you can write a fallback value first and the modern one after it. For larger changes, wrap the enhancement in @supports. Check support data before relying on a feature, and treat a feature as safe for general use once it works in all major browsers you target (the "Baseline" label on compatibility tables summarizes this). See Feature Queries.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the specificity of nav ul li.active a:hover?

    Two in the middle column (.active and :hover) and four types (nav, ul, li, a).
  2. 2. Two stacked paragraphs have margin-bottom: 30px and margin-top: 20px. How big is the gap?

    Adjacent vertical margins collapse into the larger of the two.
  3. 3. Which declaration does NOT create a stacking context?

    A positioned element needs a z-index other than auto to form a stacking context; the other three create one on their own.
  4. 4. With @layer a, b;, which wins: a normal declaration in layer b or a normal declaration in unlayered CSS?

    For normal declarations, unlayered styles beat every layer, before specificity is compared.

Summary

  • Junior questions test the fundamentals: the box model, box-sizing, specificity, the cascade, inheritance, display types and units.
  • Mid-level questions focus on layout and reasoning: flexbox versus grid, positioning, stacking contexts, responsive techniques and performance-friendly animation.
  • Senior questions are about systems: cascade layers, CSS architecture, :has(), loading performance, formatting contexts, logical properties and browser support strategy.
  • Answer with the why, give a short example, and mention trade-offs; that's what interviewers listen for.
  • Any answer you couldn't give confidently points to a lesson worth revisiting.

You've reached the end of the CSS course. Revisit the cheat sheet whenever you need a quick reminder, keep sharpening your skills with the exercises, and when you're ready to make your pages interactive, continue with the JavaScript course.