Command Palette

Search for a command to run...

Hectal
PHASE 11Advanced ~26 min· topic 8 of 8

Topic 11.8

CSS Interview Questions

In one line

The CSS questions interviewers ask most (specificity, the box model, Flexbox vs Grid, positioning and block formatting contexts) each have a short, precise model answer; learn the answer, the example that proves it, and the follow-up they usually ask next.

Think of it like this

A driving test. The examiner doesn't ask you to recite the whole rulebook; they ask a few standard questions and watch whether you understand why each rule exists. CSS interviews work the same way. A handful of questions come up again and again, and a great answer has three parts: a one-sentence definition, a tiny example, and a real-world consequence ("that's why z-index: 9999 sometimes doesn't work").

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Specificity
A score (a, b, c) for a selector: IDs, then classes/attributes/pseudo-classes, then element names.
Box model
The four layers of every element's box: content, padding, border, margin.
`box-sizing`
Decides whether width and height include padding and border (border-box) or not (content-box).
One-dimensional layout
Arranging items along one line, a row or a column, like Flexbox.
Two-dimensional layout
Arranging items in rows and columns at once, like Grid.
Containing block
The rectangle an element's position and percentage sizes are measured against.
Positioned element
An element whose position is anything other than static.
Block formatting context (BFC)
An independent layout region that contains its floats and stops margins collapsing through it.
Stacking context
A group of elements stacked as one layer; z-index only orders things inside the same group.

Step by step

01Score specificity out loud

Count IDs, then classes, attributes and pseudo-classes, then elements and pseudo-elements. #nav .item:hover > a::before is 1 ID, 2 (class + pseudo-class), 2 (element + pseudo-element): (1,2,2).

specificity.csswhole filecss
p                     /* (0,0,1) */
.note                 /* (0,1,0) */
p.note[data-x]        /* (0,2,1) */
#main .note           /* (1,1,0) */
:where(#main) .note   /* (0,1,0): :where adds nothing */
:is(#main, p) .note   /* (1,1,0): strongest argument */

02Draw the box

Content in the middle, then padding, border, margin. Then say which of them width covers under each box-sizing.

Draw the boxdiagram
Rendering diagram…

03Pick Flexbox or Grid

Ask: is this a line of things sized by their content, or a structure the container defines in rows and columns? Then name a real example of each.

04Find the containing block

For an absolute element, walk up the tree to the first positioned ancestor. That ancestor's padding box is the containing block. No positioned ancestor means the initial containing block (the size of the viewport, at the top of the page).

Find the containing blockdiagram
Rendering diagram…

05Explain a BFC with floats

Show a parent with only floated children: its height is 0. Give it display: flow-root, it becomes a BFC, and its height wraps the floats. That's the whole idea in one example.

Try it yourself

  1. 1

    Out-score the ID

    In the specificity duel, without using an ID or an inline style, make royalblue win. Predict which tools work (!important, a cascade layer around the other rules) before trying them.

  2. 2

    Other ways to make a BFC

    In the BFC example, replace display: flow-root with overflow: hidden, then with display: inline-block. Predict the height each time and what other side effect each one has.

  3. 3

    Move the containing block

    In the positioning example, set the card back to relative and add position: relative to .outer too. Predict where the badge goes now (the nearest positioned ancestor wins).

Code & diagrams

Specificity duel New tab

One ID (1,1,0) beats any number of classes, so crimson wins although three rules come later. An inline style beats every selector.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

winner: rgb(220, 20, 60)
after an inline style: rgb(128, 0, 128)
content-box vs border-box New tab

Same `width: 200px`. With content-box the drawn box is 200 + 2×20 + 2×5 = 250px; with border-box it is 200px and the content area shrinks to 150px.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

content-box -> drawn width: 250px
border-box -> drawn width: 200px
A block formatting context contains floats New tab

Floats are taken out of normal flow, so a normal parent ignores them and collapses to 0px. `display: flow-root` creates a BFC, which includes floats in its height.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

normal parent height: 0px
flow-root parent height: 80px
Absolute positioning and the containing block New tab

With `position: relative` on the card, the badge sits in the card's corner. Make the card `static` and the badge jumps to the corner of the page, because no ancestor is positioned (its `offsetParent` becomes `<body>`).

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

offsetParent: card
after card is static: body

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Expect many classes to beat one ID

In the specificity duel, add .note.note.note.note.note.note.note.note.note.note.note { color: gold; } (eleven classes).

terminal
$ Console
── what you'll see ──
winner: rgb(220, 20, 60)

Break #2

Clear floats with overflow: hidden and lose a dropdown

In the BFC example, use overflow: hidden on .bfc and add an absolutely positioned menu that should hang below the parent.

terminal
$ Look at the page
── what you'll see ──
The parent now contains the float, but the menu is cut off at the parent's edge.

Myth vs fact

Myth

Specificity is a single number like 110.

Fact

It's three separate columns compared left to right. No number of classes ever beats one ID.

Myth

Grid replaced Flexbox.

Fact

They solve different problems: Flexbox for one-dimensional, content-sized rows or columns; Grid for two-dimensional structure. Real layouts use both.

Myth

position: absolute is relative to the parent.

Fact

It's relative to the nearest positioned ancestor, which may be much further up, or the initial containing block if there is none.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    Interviewers often probe the cascade order beyond specificity: origin and importance (with !important user-agent and user styles beating author ones), then cascade layers, then specificity, then order of appearance. Mentioning layers and :where() signals current knowledge.

  • ▸

    fixed and absolute descendants use an ancestor with transform, perspective, filter, contain: paint or will-change: transform as their containing block, which is why a modal inside a transformed card stops covering the viewport. Mount modals at the end of <body>, or use <dialog> and the top layer.

  • ▸

    Margins don't collapse inside flex and grid containers, and flex and grid items each establish an independent formatting context for their contents. That's why many "weird spacing" bugs disappear when a parent becomes display: flex.

  • ▸

    For width: 100% plus padding overflowing its parent, the answer is box-sizing: border-box, which is why nearly every reset applies it to everything: *, *::before, *::after { box-sizing: border-box; }.

Remember this

  1. 1

    Specificity decides which selector wins when declarations conflict in the same origin and layer. It's a score of three numbers (a, b, c): a counts ID selectors; b counts classes, attribute selectors and pseudo-classes; c counts element names and pseudo-elements. Compare left to right: (1,0,0) beats (0,10,0). The universal selector * and combinators add nothing; :where() adds zero; :is(), :not() and :has() add their strongest argument. Inline styles beat all selectors, !important beats normal declarations, and before specificity the cascade checks origin, importance and layers (Phase 2).

  2. 2

    The box model: every element is a rectangle made of content, padding, border and margin, from the inside out. With the default box-sizing: content-box, width sets only the content, so padding and border are added on top: width: 200px; padding: 20px; border: 5px draws a 250px box. With box-sizing: border-box, width includes padding and border, so the box is 200px and the content shrinks to 150px. Margins are outside the box and vertical ones can collapse (Phase 5).

  3. 3

    Flexbox vs Grid: Flexbox is one-dimensional; it lays items out along one axis (a row or a column) and lets content decide sizes, with wrapping as an afterthought. Grid is two-dimensional; you define rows and columns and place items into them, so items line up in both directions. A useful rule: content out (let items decide their size, like a nav bar or a row of tags) means Flexbox; layout in (the container defines the structure, like a page layout or a card gallery) means Grid. They combine freely: a grid of cards whose insides are flex.

  4. 4

    Positioning: static is normal flow (the default; top/left and z-index don't apply). relative keeps the element's space in the flow and shifts it visually; it also makes it the containing block for absolute children. absolute removes the element from the flow and places it relative to the nearest positioned ancestor (any position other than static), or the initial containing block. fixed is placed relative to the viewport (unless an ancestor has a transform, filter or similar). sticky acts like relative until a scroll threshold, then sticks within its scrolling container and its parent's box.

  5. 5

    A block formatting context (BFC) is an independent layout region where block boxes are laid out vertically and floats are kept inside. An element that creates a BFC contains its floats (its height includes them), doesn't let its children's margins collapse with its own, and doesn't overlap floats outside it. Things that create one: the root <html>, floats, position: absolute or fixed, display: inline-block, flow-root, table cells, overflow other than visible (and clip), flex and grid items, and contain: layout. The modern, side-effect-free way is display: flow-root.

  6. 6

    Expect follow-ups that connect these: stacking contexts (z-index only compares siblings inside the same context; opacity < 1, transform, filter, positioned elements with a z-index, and others create one), **em vs rem** (em is relative to the element's own font size, or the parent's for font-size itself; rem to the root's), centering (grid with place-items: center, or flex with both alignments), **display: none vs visibility: hidden vs opacity: 0 (removed from layout and accessibility; keeps space but hidden from both; keeps space and is still clickable and announced), and performance** (animate transform and opacity).

Explain it without notes

01

How is CSS specificity calculated? Give examples, including :is(), :where() and inline styles.

02

Explain the CSS box model and the difference between content-box and border-box.

03

When would you use Flexbox and when Grid?

04

Explain the values of position and what the containing block is for each.

05

What is a block formatting context, how do you create one, and what problems does it solve?

Practice

01

Order these selectors from weakest to strongest: ul li a, .menu a, #top a, :where(#top) a.link, a:hover.

02

A box has width: 300px; padding: 16px; border: 2px solid; margin: 10px; with default box-sizing. How wide is it on screen, and how much horizontal space does it take including margins? What changes with border-box?

03

Write CSS to place a close button in the top-right corner of a .modal, 8px from each edge.

Trade-offs

  • ↔

    A short, memorised answer shows you know the definition; a short example plus a real consequence shows you can use it. Practise both, out loud.

  • ↔

    Interview answers simplify: say "usually" where the spec has exceptions (sticky inside overflow, fixed inside transforms) rather than over-claiming.

Done when you can

  • I can calculate specificity, including :is(), :where() and :not().

  • I can draw the box model and compute sizes for both box-sizing values.

  • I can choose Flexbox or Grid and justify it with an example.

  • I can explain each position value and find any element's containing block.

  • I can explain what a BFC is, list ways to create one, and show it containing floats.

  • I can answer follow-ups on stacking contexts, em vs rem and hiding elements.