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
widthandheightinclude 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
positionis anything other thanstatic. - 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-indexonly 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).
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.
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).
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
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
Other ways to make a BFC
In the BFC example, replace
display: flow-rootwithoverflow: hidden, then withdisplay: inline-block. Predict the height each time and what other side effect each one has. - 3
Move the containing block
In the positioning example, set the card back to
relativeand addposition: relativeto.outertoo. Predict where the badge goes now (the nearest positioned ancestor wins).
Code & diagrams
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
Console
Nothing logged yet.Expected console output
winner: rgb(220, 20, 60)
after an inline style: rgb(128, 0, 128)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
Console
Nothing logged yet.Expected console output
content-box -> drawn width: 250px
border-box -> drawn width: 200pxFloats 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
Console
Nothing logged yet.Expected console output
normal parent height: 0px
flow-root parent height: 80pxWith `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
Console
Nothing logged yet.Expected console output
offsetParent: card
after card is static: bodyBreak 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).
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.
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
!importantuser-agent and user styles beating author ones), then cascade layers, then specificity, then order of appearance. Mentioning layers and:where()signals current knowledge. - ▸
fixedandabsolutedescendants use an ancestor withtransform,perspective,filter,contain: paintorwill-change: transformas 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 isbox-sizing: border-box, which is why nearly every reset applies it to everything:*, *::before, *::after { box-sizing: border-box; }.
Remember this
- 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,!importantbeats normal declarations, and before specificity the cascade checks origin, importance and layers (Phase 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,widthsets only the content, so padding and border are added on top:width: 200px; padding: 20px; border: 5pxdraws a 250px box. Withbox-sizing: border-box,widthincludes 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
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
Positioning:
staticis normal flow (the default;top/leftandz-indexdon't apply).relativekeeps the element's space in the flow and shifts it visually; it also makes it the containing block for absolute children.absoluteremoves the element from the flow and places it relative to the nearest positioned ancestor (anypositionother than static), or the initial containing block.fixedis placed relative to the viewport (unless an ancestor has atransform,filteror similar).stickyacts like relative until a scroll threshold, then sticks within its scrolling container and its parent's box. - 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: absoluteorfixed,display: inline-block,flow-root, table cells,overflowother thanvisible(andclip), flex and grid items, andcontain: layout. The modern, side-effect-free way isdisplay: flow-root. - 6
Expect follow-ups that connect these: stacking contexts (
z-indexonly compares siblings inside the same context;opacity < 1,transform,filter, positioned elements with az-index, and others create one), **emvsrem** (emis relative to the element's own font size, or the parent's forfont-sizeitself;remto the root's), centering (grid withplace-items: center, or flex with both alignments), **display: nonevsvisibility: hiddenvsopacity: 0(removed from layout and accessibility; keeps space but hidden from both; keeps space and is still clickable and announced), and performance** (animatetransformandopacity).
Explain it without notes
How is CSS specificity calculated? Give examples, including :is(), :where() and inline styles.
Explain the CSS box model and the difference between content-box and border-box.
When would you use Flexbox and when Grid?
Explain the values of position and what the containing block is for each.
What is a block formatting context, how do you create one, and what problems does it solve?
Practice
Order these selectors from weakest to strongest: ul li a, .menu a, #top a, :where(#top) a.link, a:hover.
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?
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-sizingvalues.I can choose Flexbox or Grid and justify it with an example.
I can explain each
positionvalue 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,
emvsremand hiding elements.