HTML & CSS NotesRohit’s interview study guide
Practice

All questions

Every interview answer and quiz card in HTML & CSS, in one place: 113 interview answers and 115 quiz cards from 13 chapters. Try each one out loud before you open its answer; “Open in topic” takes you to the full explanation.

How does the browser parse HTML?

Show answer

It decodes bytes into characters using the declared encoding, tokenizes them into start tags, end tags, text and comments, and a tree builder turns that token stream into the DOM. The parser never throws: HTML5 specifies exact error-recovery rules, so every browser builds the same DOM even from broken markup, for example auto-closing a p when a div starts, or moving stray text out of a table. The doctype only picks the rendering mode: <!doctype html> means standards mode, no doctype means quirks mode. Parsing is incremental, so the browser can start fetching resources and rendering before the whole file has arrived, and a classic <script> pauses it.

Open in topic →

Why can't the script find the button?

HTML
<head>
  <script src="app.js"></script>
</head>
<body>
  <button id="buy">Buy</button>
</body>

app.js runs document.getElementById("buy").addEventListener("click", …) and throws TypeError: Cannot read properties of null. Why, and what are two fixes?

Show answer

The script runs before the button exists.

What’s happening
  1. The parser reaches the <script> in the head and stops: a classic script must run before parsing continues, because it could call document.write.
  2. At that moment the DOM has html, head and the script; there is no body yet, so getElementById("buy") returns null and .addEventListener throws. (The demo above measured this: the head script couldn't find #last.)
  3. Fix 1: add defer. The script still downloads early, but it runs after parsing, when the button exists. type="module" behaves the same way.
  4. Fix 2: move the script to the end of <body>, which also works but discovers the download later. Wrapping the code in a DOMContentLoaded listener works too, but the parser still blocks while the file downloads.
Open in topic →

defer vs async

Show answer

A plain script blocks the parser while it downloads and runs. Both defer and async download in parallel with parsing; the difference is when they run. defer scripts run after the document has been parsed, in the order they appear, just before DOMContentLoaded, so they're right for application code that needs the DOM and depends on other scripts. async scripts run the moment they arrive, in any order, so they suit independent things like analytics. Module scripts are deferred by default. Neither attribute does anything on an inline script.

Open in topic →

Why does semantic HTML matter?

Show answer

Because the element you choose decides the role, keyboard behaviour and default features the browser gives you, not just the default look. A div styled as a button looks right but has the role generic, isn't focusable and doesn't respond to Enter or Space, so it's broken for keyboard and screen-reader users unless you rebuild all of that with ARIA and JavaScript. Native elements give landmarks and headings that people navigate by, form behaviour, and structure that search engines, reader modes and translation tools understand. It also makes the code self-describing. My rule is: pick the element for meaning, then style it however the design needs.

Open in topic →

article or section?

A blog's home page shows ten post previews, each with a title, an excerpt and a "Read more" link. A single post page has a "Comments" area with many comments. Which elements would you use for the previews, the comments area and each comment?

Show answer

Each preview is an article, the comments area is a section, and each comment is an article (nested in the post's article, or in the section).

What’s happening
  1. A preview makes sense on its own: you could show it in a feed or a search result unchanged. That's the article test.
  2. The comments area isn't a standalone piece; it's a themed part of the post, with a heading like "Comments". That's a section (give it aria-labelledby pointing at its heading if it should be a region landmark).
  3. Each comment is self-contained again (author, date, text), so each is an article. The spec explicitly allows nested articles: an inner article is related to the outer one, like a comment to its post.
  4. If you only needed a flex wrapper around the previews, that wrapper is a div (or a ul with each article in an li, since it's a list of posts).
Open in topic →

Explain the HTML5 sectioning elements

Show answer

They describe the page's regions so assistive tech and other tools can navigate them. header and footer at page level become the banner and contentinfo landmarks, but inside an article or section they're just that section's header and footer. nav is a block of major navigation, main is the page's unique content and there should be one, and aside is tangential content like a sidebar. article is self-contained content that could stand alone, like a post or a card; section is a themed part of a larger whole and should have a heading, and it only becomes a region landmark when it has an accessible name. When I just need a box for layout, I use a div.

Open in topic →

What's wrong with this markup?

HTML
<div class="title">Settings</div>
<h4>Profile</h4>
<p>…</p>
<h4>Notifications</h4>
<p>…</p>
Show answer

There's no h1, and the section headings jump straight to level 4.

What’s happening
  1. "Settings" is the page title but it's a div, so it isn't in the heading outline at all. A screen-reader user pulling up the headings list sees only "Profile" and "Notifications", both level 4, and has to guess what the page is.
  2. h4 was probably chosen because its default size looked right. That's choosing the level by size, and it implies two missing levels above it.
  3. Fix: <h1>Settings</h1>, then <h2>Profile</h2> and <h2>Notifications</h2>, and set the sizes in CSS (h2 { font-size: 1rem; }) if the design wants them small.
  4. If "Settings" is visually a small breadcrumb-like label and the design has no visible title, you can still keep a real h1 and style it, rather than dropping it.
Open in topic →

How should headings be structured?

Show answer

Headings are the page outline, and screen-reader users navigate by them, so the level must reflect structure, not size. I use one h1 for what the page is, h2 for major sections, h3 for subsections, and I never skip a level going down; going back up is fine. If a heading should look smaller or bigger, that's CSS. The HTML5 outline algorithm that let you restart at h1 in every section was never implemented for assistive tech and was removed from the spec, so explicit levels are the only reliable way. I check pages with an outline tool or a quick script that flags skipped levels.

Open in topic →

What does this render as?

HTML
<p>Shipping options:
  <ul>
    <li>Standard</li>
    <li>Express</li>
  </ul>
</p>

How many p elements are in the DOM, and where is the list?

Show answer

Two p elements: the first holds "Shipping options:", then the ul as its sibling, then an empty p.

What’s happening
  1. The parser opens the p and adds the text.
  2. <ul> is flow content that isn't phrasing, so a ul start tag closes the open p first. The list becomes the p's next sibling, not its child.
  3. The final </p> has no open p. The spec's rule is to insert an empty p element there, so you get <p></p> after the list.
  4. Result: p (text), ul, p (empty). CSS like p ul { … } never matches, and the empty p adds an extra paragraph margin. Fix: end the p before the list, or use a div as the wrapper.
Open in topic →

Block vs inline, and the content model

Show answer

Block and inline are CSS display types: block elements start on a new line and take the available width and honour width and height, inline elements flow within a line and ignore width and height. The content model is HTML's separate set of rules about nesting: a p can only hold phrasing content, a ul only lis, and interactive elements can't be nested. Changing display doesn't change the content model. Some violations get silently repaired by the parser, like a div inside a p splitting the paragraph, and others, like a button inside a link, stay in the DOM and cause inconsistent behaviour, so I validate markup rather than trusting what renders.

Open in topic →

When do you use a link and when a button?

Show answer

A link navigates: it has an href, so it can be opened in a new tab, copied and bookmarked, and assistive tech announces it as a link that activates with Enter. A button performs an action on the current page, like opening a dialog or submitting a form, and activates with Enter or Space. Using <a href="#"> for actions or a button with location.href for navigation breaks those expectations for keyboard and screen-reader users. For target="_blank", modern browsers apply noopener by default, but I'd still mention the tabnabbing risk and that rel="noopener noreferrer" was the fix.

Open in topic →

What should the alt text be?

  1. A company logo in the header that links to the home page.
  2. A decorative wave graphic between two sections.
  3. A photo of the product on a product page, next to the product name.
  4. A screenshot of an error dialog in a help article, with the error text already in a paragraph below it.
Show answer

1: alt="Acme home", 2: alt="", 3: a short description of what the photo shows that the text doesn't, 4: alt="" or a brief alt, because the text already carries the information.

What’s happening
  1. The logo is the only content of a link, so its alt is the link's accessible name. It must describe the destination: "Acme home" (or just "Acme" if it's understood that the logo goes home). "Acme logo" tells a screen-reader user what the image is but not where the link goes.
  2. The wave is decoration with no information, so alt="": screen readers skip it. Omitting alt entirely would be worse; some screen readers would read the file name.
  3. The product photo is informative: "Black Pixel Watch 3 with a grey sport band, side view". Don't repeat the product name that's already next to it.
  4. The screenshot's information is already in the text, so it's effectively decorative here: alt="", or a short alt="Screenshot of the error dialog" if it helps orientation. Repeating the full error text would make screen-reader users hear it twice.
Open in topic →

How do you handle images well?

Show answer

Every img gets an alt: a short description of what the image conveys in context, or an empty alt="" if it's decorative, so screen readers skip it. I always set width and height: browsers turn them into a default aspect ratio, so the right space is reserved before the image loads and there's no layout shift, even with width: 100%; height: auto. Below-the-fold images get loading="lazy", the hero image doesn't, and may get fetchpriority="high". For different screen sizes and formats I use srcset/sizes or <picture>. And charts or diagrams get a figure with a figcaption or nearby text carrying the details.

Open in topic →

Table or not?

Which of these should be a <table>: (a) a product grid of 12 cards, (b) a comparison of three phones across battery, weight and price, (c) a two-column form with labels on the left and inputs on the right, (d) a monthly calendar?

Show answer

(b) and (d) are tables; (a) and (c) aren't.

What’s happening
  1. (a) Cards are a list of independent items laid out in a grid. There are no column headers that give a cell its meaning, so it's a ul of articles laid out with CSS grid.
  2. (b) Every value is meaningful only with its row header (the phone) and column header (battery, weight, price). That's tabular data: th scope="col" for the attributes, th scope="row" for the phones, and a caption.
  3. (c) Label–input pairs are a form, not data. Use label elements and lay them out with grid; a table would add meaningless "row, column" announcements.
  4. (d) A calendar is genuinely two-dimensional: weekday columns and week rows, and "Tuesday the 14th" depends on both. A table with weekday ths is the accessible choice.
Open in topic →

How do you make an accessible data table?

Show answer

I use a real table only for two-dimensional data, give it a caption so it has a name, group rows with thead and tbody, and mark header cells as th with scope="col" or scope="row" so screen readers announce the right headers as the user moves between cells. For complex multi-level headers I use headers with ids. I never use tables for layout; if a legacy one exists, role="presentation" removes its table semantics. For small screens I prefer letting the table scroll horizontally over restyling its parts with display, which can break the semantics.

Open in topic →

What are data attributes and how do you use them?

Show answer

data-* attributes let you attach custom data to any element without inventing invalid attributes. In JavaScript they appear in element.dataset, with the data- prefix removed and dash-case converted to camelCase, so data-user-id becomes dataset.userId; all values are strings. In CSS you can select on them, like [data-state="open"], which makes them a clean bridge between script state and styles. I keep them small and non-sensitive, and use real attributes or ARIA states where those exist.

Open in topic →

What happens here?

HTML
<button popovertarget="a">A</button>
<button popovertarget="b">B</button>
<div id="a" popover>Menu A</div>
<div id="b" popover="manual">Panel B</div>

You click A, then B, then click on an empty part of the page. What's open at each step?

Show answer

After A: Menu A. After B: Menu A closes (the click landed outside it, which light-dismisses it) and Panel B opens. After clicking the page: Panel B is still open.

What’s happening
  1. Clicking A toggles #a, an auto popover, so Menu A opens in the top layer.
  2. Clicking B: the click is outside Menu A, so light dismiss closes Menu A. Then B's popovertarget opens #b. It's manual, so it doesn't take part in auto-popover closing.
  3. Clicking the empty page: light dismiss only applies to auto popovers, so Panel B stays open. It closes when you click B again (popovertarget toggles by default) or call hidePopover().
  4. If #b were also an auto popover, the result after step 2 would be the same (A closes, B opens), but clicking the page in step 3 would close B too.
Open in topic →

How would you build a modal today?

Show answer

I'd use a <dialog> and open it with showModal(), or a button with command="show-modal" where invoker commands are supported. showModal() puts it in the top layer above every stacking context, adds a stylable ::backdrop, makes the rest of the page inert so focus and screen readers stay inside, moves focus into the dialog and closes on Escape. A form method="dialog" inside closes it and sets returnValue to the button's value. I give it an accessible name with aria-labelledby pointing at its heading, and return focus sensibly when it closes. For menus and tooltips that should close when you click away, I'd use the popover attribute instead, which also uses the top layer but doesn't make the page inert.

Open in topic →

What does the server receive?

HTML
<form action="/prefs" method="get">
  <input type="checkbox" name="email_updates" value="yes">
  <input type="checkbox" name="topics" value="css" checked>
  <input type="checkbox" name="topics" value="html" checked>
  <input name="nickname" value="Ro" readonly>
  <input name="plan" value="pro" disabled>
  <button>Save</button>
</form>
Show answer

/prefs?topics=css&topics=html&nickname=Ro

What’s happening
  1. email_updates is unchecked, so it's left out entirely; the server never sees the key.
  2. Both topics checkboxes are checked, so the key appears twice: topics=css&topics=html. Servers differ in how they read repeated keys (PHP needs the name topics[]; Express with qs gives an array; URLSearchParams.get returns only the first, getAll returns both).
  3. nickname is readonly, which only stops editing: it's still submitted. plan is disabled, so it's excluded. If you want a field shown but not editable and sent, use readonly.
  4. The button has no name, so it adds nothing. This is the same rule set the demo above measured: name required, not disabled, checked if checkable.
Open in topic →

What happens when a form is submitted?

Show answer

The browser runs constraint validation first, unless the form has novalidate or the button has formnovalidate, then fires a submit event that scripts can cancel. If it isn't cancelled, it builds the form data set: every control with a name that isn't disabled, checkboxes and radios only if checked, and the button that was pressed. It encodes that list according to enctype, urlencoded by default or multipart for files, and navigates to action: GET puts the data in the query string, POST puts it in the body. GET suits searches you want to bookmark; POST suits anything that changes state or is sensitive. In JavaScript I listen for submit, call preventDefault(), and send new FormData(form) with fetch.

Open in topic →

What's wrong with this field?

HTML
<div class="field">
  <span class="field-label">Email</span>
  <input type="email" name="email" placeholder="Email">
</div>
Show answer

The visible "Email" text isn't associated with the input, so the field's name comes only from the placeholder, and clicking "Email" doesn't focus it.

What’s happening
  1. A span next to an input is just text; the browser has no idea it describes the input.
  2. With nothing else, Chrome names the field from its placeholder, "Email", which is why automated checks may not catch it. But the placeholder vanishes once the user types, and other browser and screen-reader combinations don't all use it.
  3. Clicking the visible "Email" text does nothing, so the click target is only the input itself.
  4. Fix: make the span a <label for="email"> and give the input id="email" (or wrap the input in the label), and drop the redundant placeholder or use it for an example like "name@example.com".
Open in topic →

How do you label form fields accessibly?

Show answer

Every control needs a visible label associated with it, either <label for> pointing at the input's id or a label wrapping the input. That gives screen readers the field's name and makes the label text a click target that focuses or toggles the control. A placeholder isn't a substitute: it disappears when you type, usually has poor contrast and isn't reliably announced. Where there's no room for visible text, I use aria-label or aria-labelledby, keeping in mind they don't create a click target. Help text and errors go in separate elements connected with aria-describedby.

Open in topic →

What do input types give you?

Show answer

The type sets the keyboard or picker the user gets, how the value is sanitised and validated, and the role assistive tech announces. For example email trims spaces and checks for an @, number gives a spinbutton and sanitises non-numbers to an empty string, date always gives you yyyy-mm-dd regardless of locale, and url requires a scheme. Unknown types fall back to text, so it degrades safely. I add autocomplete tokens so autofill and password managers work, which is also a WCAG requirement, and inputmode when I only want a different keyboard without changing validation, like inputmode="numeric" on a one-time code.

Open in topic →

Which fields block the submit?

HTML
<form>
  <input name="a" type="email" value="ro@hit">
  <input name="b" type="number" min="0" max="100" step="10" value="35">
  <input name="c" pattern="[A-Z]{2}" value="ca">
  <input name="d" required disabled>
  <input name="e" type="text" maxlength="3" value="abcdef">
</form>
Show answer

b and c block it. a, d and e don't.

What’s happening
  1. a: ro@hit is a valid email for the browser; a dot in the domain isn't required.
  2. b: steps of 10 from min="0" allow 0, 10, 20, 30, 40… so 35 has stepMismatch. Blocks.
  3. c: patterns are case-sensitive and anchored, so ca doesn't match [A-Z]{2}. Blocks.
  4. d: disabled controls are barred from validation, so required is ignored (and it isn't submitted either).
  5. e: maxlength stops the user typing more than 3 characters, but a longer value set in markup isn't flagged (tooLong is only set for user edits, like minlength in the demo). It's submitted as abcdef, which is one more reason the server must validate.
Open in topic →

How does HTML form validation work?

Show answer

You declare constraints with attributes: required, minlength and maxlength, min, max and step, pattern, and types like email and url. Each one sets a flag on the control's ValidityState, which drives the :valid and :invalid pseudo-classes. On submit the browser checks every candidate control; disabled and readonly ones are skipped, and if anything fails it cancels the submit, focuses the first invalid field and shows a message. novalidate on the form or formnovalidate on a button turns that submit-time check off. It's a usability layer only, so the server always validates again.

Open in topic →

What does this log?

JavaScript
const input = document.createElement("input");
input.required = true;
console.log(input.checkValidity());
input.value = "x";
input.setCustomValidity("Taken");
console.log(input.checkValidity(), input.validationMessage);
input.value = "y";
console.log(input.validity.valid);
input.setCustomValidity("");
console.log(input.validity.valid);
Show answer

false, then false "Taken", then false, then true.

What’s happening
  1. A required input with no value has valueMissing, so checkValidity() is false (and an invalid event fires on it). It doesn't need to be in a form or in the document.
  2. Setting the value fixes valueMissing, but setCustomValidity("Taken") adds customError, so it's still false, and validationMessage is "Taken".
  3. Changing the value to "y" doesn't clear the custom error; only another setCustomValidity call does. Still false.
  4. setCustomValidity("") removes it, and with a value present, valid is true.
Open in topic →

How do you add custom validation rules?

Show answer

I keep the browser's constraint system and extend it with setCustomValidity. For a rule like "passwords must match", I check on every input event and call setCustomValidity with a message when it fails and with an empty string when it passes; the field then behaves exactly like a built-in failure, including :invalid, checkValidity() and blocking the submit. The key gotcha is that the custom message never clears itself. I use checkValidity() to test silently and reportValidity() when I want the browser to show the message and focus the field, and if I render my own messages I add novalidate and read the validity flags. The invalid event doesn't bubble, so a form-level listener needs capture.

Open in topic →

:invalid vs :user-invalid

Show answer

:invalid matches whenever the control's value fails a constraint, including on page load, so required fields are red before the user has done anything. :user-invalid matches only after the user has interacted with the field, by changing it and moving on, or after a submit attempt, which then flags every invalid field at once. That's the behaviour designers actually want, and it's Baseline and widely available now. Before it, the options were a JavaScript touched class added on blur or the :not(:placeholder-shown):invalid trick. I'd combine it with :has() to style the label and error text from the input's state.

Open in topic →

Why does the page reload?

HTML
<form id="cart">
  <ul id="items"></ul>
  <button onclick="addItem()">Add item</button>
  <button type="submit">Checkout</button>
</form>

Clicking "Add item" adds an li and then the page reloads, and the item is gone. Why?

Show answer

"Add item" has no type, so it's a submit button: after the click handler runs, the form submits and the page navigates.

What’s happening
  1. The click runs addItem(), which adds the li.
  2. Then the button's default action runs: a <button> defaults to type="submit", so it submits #cart.
  3. The form has no action, so it submits to the current URL with GET, which reloads the page and loses the DOM change.
  4. Fix: <button type="button" onclick="addItem()">. Calling event.preventDefault() in the handler also works, but the type makes the intent obvious.
Open in topic →

What's the default type of a button?

Show answer

submit. A <button> without a type inside a form submits it, which is a classic bug for buttons meant to toggle something or add a row, so I always write type="button" for those. type="reset" restores the initial values from the markup, and I rarely use it. Buttons can override the form for one submission with formaction, formmethod, formenctype, formnovalidate and formtarget, which is how you do "Save draft" next to "Publish", and the form attribute lets a button outside the form element, say in a sticky footer, submit it. Pressing Enter in a field submits the form using its first submit button.

Open in topic →

Does this group need a fieldset?

A sign-up form has: an "I agree to the terms" checkbox, a "How did you hear about us?" set of five checkboxes, a date of birth split into day, month and year inputs, and a single "Email" field.

Show answer

The five checkboxes and the date of birth need fieldsets; the single checkbox and the email field don't.

What’s happening
  1. "I agree to the terms" is one control whose label says everything. A fieldset adds nothing.
  2. The five checkboxes answer one question, which none of their labels ("Search engine", "Friend", …) states on its own. A fieldset with legend "How did you hear about us?" makes each option understandable.
  3. Day, month and year are three inputs for one value. Labels "Day", "Month", "Year" need the context "Date of birth": a fieldset with that legend provides it (or use a single type="date" input instead).
  4. The email field has its own label and stands alone. Wrapping single fields in fieldsets just adds noise for screen-reader users.
Open in topic →

When do you use fieldset and legend?

Show answer

Whenever several controls answer one question: radio groups, related checkboxes, or a value split across inputs like a date or an address. The fieldset exposes a group whose name is the legend, so screen readers announce the question along with each option. A disabled fieldset disables every control inside it, apart from those in its first legend, which means they can't be focused, aren't validated and aren't submitted. That's a neat way to toggle a whole section. Fieldsets have odd default styles, so I reset them rather than replacing them with divs.

Open in topic →

select or datalist?

Which would you use for: (a) a T-shirt size (S, M, L, XL), (b) a "Job title" field where you'd like to suggest common titles, (c) a country with 195 options, (d) tags for a blog post?

Show answer

(a) select (or radios), (b) datalist, (c) select, ideally with a search, (d) datalist or a custom tag input.

What’s happening
  1. (a) Sizes are a small closed set; any other value is wrong. A select, or radio buttons in a fieldset since there are only four, which shows every choice at once.
  2. (b) Titles are open-ended: suggestions help, but "Principal Android Engineer" must be allowed. That's a datalist.
  3. (c) The list is closed (an invalid country shouldn't be accepted), so select. With 195 options, typing the first letters jumps to them in a native select; for a better experience, a searchable combobox component, or the customisable select where it's supported.
  4. (d) Tags are free text with common suggestions, so a datalist gives suggestions per tag; entering several tags in one field usually needs a small custom component on top.
Open in topic →

select vs datalist, and textarea gotchas

Show answer

A select restricts the value to its options: each option's value is submitted, falling back to its text, and a first option with value="" plus required forces a real choice. With multiple, each selected option is submitted as a repeated key. A datalist attached with list only suggests values; the input still accepts anything, so it's for open-ended fields with common answers. A textarea's initial value is its content, not a value attribute, the parser drops one newline right after the opening tag, and any indentation is kept. For auto-growing textareas there's now field-sizing: content, and for styling dropdowns the customisable select with appearance: base-select, which isn't in every browser yet.

Open in topic →

How much room does this card take?

CSS
.card { width: 300px; padding: 10px; border: 2px solid; margin: 20px; }

How wide is the card's visible rectangle, and how much horizontal space does it take in the layout?

Show answer

The visible (border) box is 324px wide, and it takes 364px of horizontal space.

The card measured
CSS
.shrink { display: flow-root; width: max-content; background: #f1f5f9; }
.card { width: 300px; padding: 10px; border: 2px solid #475569; margin: 20px; background: #fff; }
HTML
<div class="shrink"><div class="card">card</div></div>
Resultlive, in your browser
What’s happening
  1. Under the default box-sizing: content-box, width: 300px is the content only.
  2. Add padding on both sides (2 × 10) and border on both sides (2 × 2): 300 + 20 + 4 = 324px, the border box the test measures.
  3. Margins sit outside that: 324 + 2 × 20 = 364px. The wrapper uses width: max-content to shrink-wrap the card including its margins, and measures 364.
Open in topic →

Explain the CSS box model

Show answer

Every element renders as a rectangular box with four areas: content, padding, border and margin. Padding and border belong to the element (the background paints under them), while margin is transparent space outside the border that separates it from neighbours. By default width and height size only the content box, so the rendered size is width plus padding plus border, and the space it occupies adds margins too. box-sizing: border-box changes that so width includes padding and border, which is why most resets set it everywhere. I'd also mention that vertical margins between blocks can collapse, and that inline elements ignore vertical margins.

Open in topic →

width: 100% plus padding

A container is 300px wide. Its child has width: 100%; padding: 0 20px and no box-sizing rule. How wide is the child, and does it fit?

Show answer

It renders 340px wide and sticks out of the container by 40px. With box-sizing: border-box it's exactly 300px.

100% wide with padding
CSS
.parent { width: 300px; background: #f1f5f9; margin-bottom: 8px; }
.child { width: 100%; padding: 0 20px; height: 30px; background: rgb(191 219 254 / 0.8); }
.fixed .child { box-sizing: border-box; }
HTML
<div class="parent"><div class="child">content-box</div></div>
<div class="parent fixed"><div class="child">border-box</div></div>
Resultlive, in your browser
What’s happening
  1. width: 100% resolves against the container's content width: 300px of content for the child.
  2. Under content-box, the 20px left and right padding is added outside that: 300 + 40 = 340px, so the child's right edge is 40px past the container's.
  3. With border-box, the 300px includes the padding and the child fits exactly. Leaving width as auto would also fit, because auto fills the space after padding and margins (see Width, height and intrinsic sizing).
Open in topic →

content-box vs border-box

Show answer

box-sizing controls what width and height measure. With the default content-box they size only the content, so padding and border are added and the element ends up bigger than its width. With border-box they size the border box, so padding and border eat into the content area and the element is exactly as wide as you said. I use border-box everywhere through a reset, usually html { box-sizing: border-box } plus *, *::before, *::after { box-sizing: inherit }, because it makes percentage and fixed widths predictable and lets a legacy component opt back out at its root.

Open in topic →

Predict the gap

CSS
.first  { margin-bottom: 40px; height: 40px; }
.spacer { margin: 10px 0 50px; }            /* empty div */
.second { margin-top: -15px; height: 40px; }

Three siblings in normal flow: .first, an empty .spacer, .second. How far is .second's top from .first's bottom?

Show answer

35px.

The gap measured
CSS
.wrap { display: flow-root; width: 200px; background: #f1f5f9; }
.first  { margin-bottom: 40px; height: 40px; background: #fde68a; }
.spacer { margin: 10px 0 50px; }
.second { margin-top: -15px; height: 40px; background: #bfdbfe; }
HTML
<div class="wrap"><div class="first"></div><div class="spacer"></div><div class="second"></div></div>
Resultlive, in your browser
What’s happening
  1. The spacer is empty, so its own margins (10 and 50) touch each other, and they also touch .first's bottom margin (40) and .second's top margin (-15). All four collapse into one margin.
  2. The largest positive margin is 50 and the most negative is -15.
  3. 50 + (-15) = 35px, which the test measures.
Open in topic →

What is margin collapsing?

Show answer

In normal block layout, vertical margins that touch are combined into a single margin equal to the largest of them, or the largest positive plus the most negative if some are negative. It happens between adjacent siblings, between a parent and its first or last child when there's no padding, border or content between them, and through empty blocks. It doesn't happen horizontally, or for flex items, grid items, floats, absolutely positioned or inline-block boxes. The common bug is a child's top margin escaping its parent; I fix it with display: flow-root on the parent, or avoid it by using gap and one-directional margins.

Open in topic →

Width on a span

HTML
<span style="width: 200px; height: 50px; padding: 10px; background: gold">Hi</span>

How wide is the gold background?

Show answer

As wide as the word "Hi" plus 20px of padding. width and height don't apply to non-replaced inline boxes.

The span measured
CSS
.ref { background: #e5e7eb; }
HTML
<span id="q" style="width: 200px; height: 50px; padding: 10px; background: gold">Hi</span>
<br><br>
<span id="ref" class="ref">Hi</span>
Resultlive, in your browser
What’s happening
  1. A <span> is inline by default, and an inline, non-replaced box takes its width from its content. width: 200px and height: 50px are ignored for layout.
  2. The test compares it with an unstyled "Hi": the gold span is exactly 20px wider, the left and right padding.
  3. The vertical padding is painted too, but it overlaps neighbouring lines instead of making room (see The box model).
  4. Add display: inline-block and the box becomes 220 × 70 (content 200 × 50 plus padding).
Open in topic →

block vs inline vs inline-block

Show answer

A block box starts on a new line, fills the available width by default, and respects width, height and all margins and padding. An inline box flows within a line of text, is sized by its content, ignores width and height, and its vertical padding and margins don't push other lines. Inline-block sits inside a line like an inline box but behaves like a block inside, so width, height and vertical spacing work; the catch is the whitespace gap between inline-blocks and baseline alignment. Modern CSS describes this as an outer display type and an inner one, display: inline flex for example, and display: none generates no box at all.

Open in topic →

Which one can still be clicked?

A modal overlay is "closed" with one of display: none, visibility: hidden or opacity: 0, and users report that clicking the page sometimes does nothing. Which one was used, and why?

Show answer

opacity: 0. The overlay is transparent but still there, covering the page and catching every click.

What’s happening
  1. display: none removes the overlay's box, so clicks reach the page.
  2. visibility: hidden keeps the box but it doesn't receive pointer events, so clicks pass through to the page (the first demo's elementFromPoint on C returned the element behind it).
  3. opacity: 0 keeps the box and its hit-testing: elementFromPoint on D returned D. An invisible full-screen overlay therefore swallows clicks, and its buttons can still be tabbed to.
  4. If you fade it out with opacity, finish with visibility: hidden (as in the fade demo) or add pointer-events: none, and for keyboard users make sure nothing inside can be focused.
Open in topic →

display none vs visibility hidden vs opacity 0

Show answer

display: none removes the element from layout and from the accessibility tree: it takes no space and can't be clicked or focused. visibility: hidden keeps the element's space but makes it invisible, non-interactive and hidden from screen readers, and a child can opt back in with visibility: visible. opacity: 0 only changes painting: the element still takes space, receives clicks, can be focused and is announced, so it's a trap as a final hidden state. For animation I fade opacity and switch visibility at the end, and for content that should be read but not seen I use a visually-hidden class.

Open in topic →

What width does fit-content give?

CSS
.parent { width: 250px; }
.child  { width: fit-content; }

The child holds four 80px inline-blocks with no whitespace between them. How wide is it, and how many rows does it use?

Show answer

250px wide, on 2 rows (three blocks fit on the first row, one on the second). The 250px is the container's width, not a multiple of 80.

The child measured
CSS
.parent { width: 250px; background: #f1f5f9; }
.child { width: fit-content; background: #dcfce7; }
.child b { display: inline-block; width: 80px; height: 20px; background: #22c55e; outline: 1px solid #fff; }
HTML
<div class="parent"><div class="child"><b></b><b></b><b></b><b></b></div></div>
Resultlive, in your browser
What’s happening
  1. min-content is 80px (one block) and max-content is 320px (four in a row). The available width is 250px.
  2. fit-content = min(320, max(80, 250)) = 250px.
  3. Inside 250px, three blocks (240px) fit on the first line and the fourth wraps. The box doesn't shrink to the 240px its widest line actually uses: shrink-to-fit takes the available width when the content doesn't fit, which is why a wrapped "fit-content" box often has empty space at its end.
Open in topic →

min-content, max-content and fit-content

Show answer

width: auto on a block is extrinsic: it fills its container. The intrinsic keywords size from the content instead: min-content is the narrowest the box can get without overflowing, so the longest word or widest image; max-content is the width with no wrapping at all; and fit-content is shrink-to-fit, min(max-content, max(min-content, available)). I use fit-content for things like a centred badge or button that should hug its text, and min-content/max-content mostly in grid tracks. For heights, percentages only work if the parent has a definite height, otherwise they behave as auto, and min-width beats max-width when they conflict.

Open in topic →

Which box can JavaScript scroll?

Four boxes have the same overflowing content, with overflow set to hidden, clip, auto and visible. You run box.scrollTop = 50 on each. Which of them end up scrolled?

Show answer

hidden and auto. clip and visible don't create a scroll container, so scrollTop stays 0.

scrollTop on each value
CSS
.box { width: 100px; height: 50px; } .box div { height: 150px; }
.h { overflow: hidden; } .c { overflow: clip; } .a { overflow: auto; } .v { overflow: visible; }
HTML
<div class="box h"><div></div></div><div class="box c"><div></div></div>
<div class="box a"><div></div></div><div class="box v"><div></div></div>
Resultlive, in your browser
What’s happening
  1. overflow: hidden clips the content but keeps a scroll position, so scrollTop = 50 works: the user can't scroll it, code can.
  2. overflow: auto is a normal scroll container: 50.
  3. overflow: clip clips without a scroll container, and visible doesn't clip at all: scrollTop stays 0 for both.
  4. This is the practical difference between hidden and clip, and why clip is the right choice when you only want to cut off decoration.
Open in topic →

overflow hidden vs clip vs auto

Show answer

Overflow never changes an element's size; it decides what happens to content that doesn't fit. visible lets it spill, hidden clips it but still makes a scroll container that code can scroll, clip clips without a scroll container so nothing can scroll it, and auto or scroll let the user scroll. Gotchas I'd mention: overflow-x: hidden makes overflow-y compute to auto, which can break sticky positioning, and any value except visible or clip creates a new block formatting context. For text, an ellipsis needs white-space: nowrap, overflow: hidden and text-overflow: ellipsis together.

Open in topic →

Nested em

CSS
body    { font-size: 16px; }
.outer  { font-size: 1.25em; }
.inner  { font-size: 0.8em; padding: 1em; }

.inner is inside .outer. What are .inner's font size and padding?

Show answer

Font size 16px, padding 16px.

The values computed
CSS
.body { font-size: 16px; }
.outer { font-size: 1.25em; }
.inner { font-size: 0.8em; padding: 1em; }
HTML
<div class="body"><div class="outer"><div class="inner">inner</div></div></div>
Resultlive, in your browser
What’s happening
  1. .outer is 1.25 × 16 = 20px (the demo uses a .body div standing in for body).
  2. .inner's font-size: 0.8em multiplies its parent's 20px: 16px.
  3. padding: 1em multiplies the element's own font size, now 16px: 16px.
Open in topic →

em vs rem vs px

Show answer

px is the CSS reference pixel: fixed, not a device pixel, and it ignores the user's default font size setting when used for type. rem is relative to the root element's font size, so it's consistent across the page and scales with the user's setting, which makes it my default for font sizes and spacing. em is relative to the element's own font size (or the parent's when used in font-size), so it compounds when nested but is useful when something should scale with its component, like button padding. Percentages depend on the property: width and padding use the containing block's width, font-size the parent's size, translate the element itself. Viewport units are 1% of the viewport, and on phones I'd use dvh or svh instead of vh.

Open in topic →

aspect-ratio and padding

CSS
.card { width: 300px; aspect-ratio: 3 / 2; padding: 10px; }

How tall is .card on screen under the default box-sizing, and under border-box?

Show answer

220px under content-box, 200px under border-box. The ratio applies to the box that box-sizing names.

The card under both box-sizing values
CSS
.card { width: 300px; aspect-ratio: 3 / 2; padding: 10px; background: #e9d5ff; margin-bottom: 8px; }
.bb { box-sizing: border-box; }
HTML
<div class="card" id="cb"></div>
<div class="card bb" id="bb"></div>
Resultlive, in your browser
What’s happening
  1. With content-box, the ratio sizes the content box: 300 wide means 200 tall. Padding adds 20px each way, so the card is 320 × 220, which isn't 3:2.
  2. With border-box, the ratio sizes the border box: 300 × 200, exactly 3:2, with the padding inside.
  3. One more reason for the border-box reset: with it, the visible box has the ratio you asked for.
Open in topic →

How do you keep images from causing layout shift?

Show answer

I give every <img> its width and height attributes and in CSS set max-width: 100%; height: auto. The browser maps those attributes to aspect-ratio: auto w / h, so it reserves the right height before the image downloads and nothing jumps when it arrives. For boxes that aren't images, like video embeds or cards, aspect-ratio: 16 / 9 does the same job and replaced the old padding-top percentage hack. When an image has to fill a box of a different shape, object-fit: cover crops it without distortion and object-position chooses the focal point, while contain letterboxes it.

Open in topic →

Which elements are crimson?

CSS
.card.featured { color: crimson; }
HTML
<div class="card featured">A</div>
<div class="card"><p class="featured">B</p></div>
<div class="featured card">C</div>
Show answer

A and C. .card.featured (no space) needs both classes on the same element; their order in the attribute doesn't matter.

The selector applied
CSS
.card.featured { color: crimson; }
HTML
<div class="card featured" id="a">A</div>
<div class="card"><p class="featured" id="b">B</p></div>
<div class="featured card" id="c">C</div>
Resultlive, in your browser
What’s happening
  1. A has both classes on one element: it matches.
  2. B's classes are split between a parent and a child. .card.featured doesn't look across elements, so neither matches. (.card .featured, with a space, would match the <p>.)
  3. C lists the classes in the other order. The class attribute is a set of words, so order is irrelevant: it matches.
Open in topic →

How do CSS selectors work?

Show answer

A selector is a pattern tested against elements. The simple selectors are type, class, id, attribute and universal, and writing them together without spaces makes a compound selector where all parts must match one element. Attribute selectors can test existence, exact values, prefixes, suffixes, substrings and word lists, with an i flag for case-insensitive matching. Browser engines match a complex selector starting from its rightmost compound and walking left through the combinators, which is why a very general rightmost part makes the engine test more elements. In practice I style with single classes to keep specificity flat, use attributes for state like [aria-expanded="true"], and avoid ids in CSS.

Open in topic →

Which items are crimson?

CSS
ul > li + li { color: crimson; }
HTML
<ul>
  <li>one</li>
  <li>two</li>
  <li>three <ul><li>nested a</li><li>nested b</li></ul></li>
</ul>
Show answer

"two", "three" and "nested b" (and "nested a" inherits crimson from "three", because color is inherited).

The rule applied
CSS
ul > li + li { color: crimson; }
li { color: black; } /* stops inheritance so only real matches turn crimson */
HTML
<ul>
  <li id="one">one</li>
  <li id="two">two</li>
  <li id="three">three <ul><li id="na">nested a</li><li id="nb">nested b</li></ul></li>
</ul>
Resultlive, in your browser
What’s happening
  1. Read right to left: an li whose previous element sibling is an li, and whose parent is a ul.
  2. "one" has no previous sibling: no match. "two" and "three" each follow an li: match.
  3. The inner list follows the same logic: "nested a" is first (no match), "nested b" follows it (match). The ul > part is satisfied by the inner ul too; > doesn't mean "the outer list".
  4. The demo adds li { color: black } so only true matches are crimson. In the question's version, "nested a" would inherit crimson from "three", which is why "the element is red" and "the selector matched" aren't the same question.
  5. li + li is a well-known way to add a separator or spacing between items without touching the first one.
Open in topic →

Explain the CSS combinators

Show answer

There are four: a space for descendants at any depth, > for direct children, + for the immediately following sibling and ~ for any following sibling with the same parent. The selector always targets the rightmost element; everything to the left is a condition on its ancestors or earlier siblings. Combinators only look down the tree and forward among siblings, so selecting a parent or a previous sibling needs :has(). In practice I prefer > or a class over long descendant chains, because descendant selectors are fragile when markup changes and they don't respect the nearest ancestor when themes are nested.

Open in topic →

nth-child or nth-of-type?

CSS
.list p:nth-child(1) { color: crimson; }
HTML
<div class="list">
  <h4>Title</h4>
  <p>First paragraph</p>
  <p>Second paragraph</p>
</div>

Which paragraph is crimson?

Show answer

Neither. The first child of .list is the h4, so no p is :nth-child(1). Use p:first-of-type or p:nth-of-type(1).

The selector applied
CSS
.list p:nth-child(1) { color: crimson; }
.list p:first-of-type { text-decoration: underline; }
h4 { margin: 0; }
HTML
<div class="list"><h4>Title</h4><p id="a">First paragraph</p><p id="b">Second paragraph</p></div>
Resultlive, in your browser
What’s happening
  1. p:nth-child(1) requires position 1 among all siblings and being a p. Position 1 is the h4, so nothing matches.
  2. p:first-of-type counts only p siblings, so it matches the first paragraph (the demo underlines it to show that).
Open in topic →

What are pseudo-classes?

Show answer

Pseudo-classes select elements by state or position the browser knows about but the markup doesn't spell out: structural ones like :first-child and :nth-child(An+B), user-action ones like :hover and :focus-visible, form-state ones like :checked, :disabled and :user-invalid, and logical ones like :is(), :not() and :has(). They count like a class in specificity. The common pitfalls are that :nth-child counts all element siblings while :nth-of-type counts one tag, that link states need the LVHA order because they tie on specificity, and that :empty doesn't match whitespace in current browsers. With :nth-child(n of S) and :has() you can now express things that used to need JavaScript.

Open in topic →

Why is there no star?

CSS
.rating::before { color: gold; font-size: 20px; }
.rating::after  { content: "★★★"; }

.rating shows three stars after its text, but nothing before it. Why?

Show answer

::before has no content, so no box is generated. Styling it does nothing until content is set (to a string, "", an image, a counter…).

What’s happening
  1. ::before and ::after start with content: normal, which for them computes to none: no box.
  2. .rating::after sets content: "★★★", so that box exists and shows the stars.
  3. .rating::before only sets colour and size, so it never exists. The no-content demo above shows the same thing: computed content: none and zero height.
Open in topic →

Pseudo-classes vs pseudo-elements

Show answer

A pseudo-class, with one colon, selects an existing element in a particular state or position, like :hover or :nth-child(2), and counts like a class in specificity. A pseudo-element, with two colons, selects a part of an element or creates a new box: ::before and ::after generate a first and last child that isn't in the DOM, and ::first-line, ::marker or ::placeholder style parts of existing content; it counts like a type selector. ::before and ::after need a content value to exist, don't work on replaced elements like <img> and <input>, and their text can end up in the accessible name, so I use them for decoration and give icons empty alt text with content: "★" / "".

Open in topic →

Which colour wins?

CSS
div p.lead        { color: crimson; } /* rule 1 */
.article .lead    { color: green; }   /* rule 2 */
body div.article p { color: navy; }   /* rule 3 */
HTML
<div class="article"><p class="lead">Text</p></div>
Show answer

Green. Rule 2 is 0-2-0, rule 3 is 0-1-3, rule 1 is 0-1-2.

The three rules
CSS
div p.lead         { color: crimson; }
.article .lead     { color: green; }
body div.article p { color: navy; }
HTML
<div class="article"><p class="lead">Text</p></div>
Resultlive, in your browser
What’s happening
  1. No rule has an id, so the first column ties at 0.
  2. Classes: rule 1 has .lead (1), rule 2 has .article and .lead (2), rule 3 has .article (1). Rule 2 wins on the second column.
  3. Rule 3 has the most type selectors (body, div, p = 3), but the third column only matters when the first two tie, and they don't.
  4. So the paragraph is green, even though rule 3 comes last and "looks" the most detailed.
Open in topic →

How does specificity work?

Show answer

Specificity is a three-part score, ids, then classes, attributes and pseudo-classes, then types and pseudo-elements, compared column by column from the left, so one id beats any number of classes. *, combinators and :where() add nothing, while :is(), :not() and :has() take the specificity of their most specific argument. It's only consulted after origin, importance, inline styles and cascade layers, and if it ties, the later rule wins. To keep a codebase maintainable I keep specificity low and flat, mostly single classes, and use :where() and @layer instead of escalating with ids or !important.

Open in topic →

Predict the cascade

CSS
p { color: green !important; }
#intro { color: crimson; }
HTML
<p id="intro" style="color: navy">Hello</p>

What colour is the paragraph?

Show answer

Green. Importance is decided before inline styles and specificity.

The rules applied
CSS
p { color: green !important; }
#intro { color: crimson; }
HTML
<p id="intro" style="color: navy">Hello</p>
Resultlive, in your browser
What’s happening
  1. Round one is origin and importance. p { color: green !important } is an important author declaration; the id rule and the inline style are normal author declarations.
  2. Important author beats normal author, so the other two are knocked out before the "inline style" and "specificity" rounds are reached.
  3. Result: green, from the least specific selector on the page.
Open in topic →

How does the cascade decide which style applies?

Show answer

For each property on each element, the browser gathers every matching declaration and compares them in order: first origin and importance (user-agent, user and author styles, with !important reversing that order and animations and transitions on top), then encapsulation context, then whether it's an inline style, then cascade layer, then specificity, then scope proximity, and finally source order. The first criterion that distinguishes them decides. It runs per property, so one element can take its colour from one rule and its padding from another. Invalid declarations are dropped at parse time, but var() errors are only found at computed-value time and make the property unset.

Open in topic →

display: initial on a div

CSS
.box { display: initial; width: 200px; height: 50px; background: gold; }
HTML
<div class="box">Hello</div>

How wide is the gold box?

Show answer

As wide as the word "Hello", not 200px. display: initial is inline, and inline boxes ignore width and height.

The box measured
CSS
.box { display: initial; width: 200px; height: 50px; background: gold; }
HTML
<div class="box" id="b">Hello</div>
Resultlive, in your browser
What’s happening
  1. initial means the property's initial value from the spec, and the initial value of display is inline, whatever the element is.
  2. As an inline box, the div ignores width: 200px and height: 50px (see display) and is only as wide as "Hello".
  3. To get the element's normal display back, use display: revert (block for a div).
Open in topic →

Inheritance and the reset keywords

Show answer

Some properties, mostly text-related like color, font and line-height, inherit the parent's computed value when nothing in the cascade sets them; box properties like margin, padding, border and background don't, and fall back to their initial value. An inherited value has no specificity, so any matching rule beats it, which is why links and form controls, which have browser styles, don't pick up your text colour or font without inherit. inherit forces the parent's value, initial gives the spec's initial value (so display: initial is inline), unset inherits or resets depending on the property, and revert goes back to the browser's stylesheet. all: unset is a quick way to strip a button, as long as you restore focus styles.

Open in topic →

Which important wins?

CSS
#nav a { color: crimson !important; }
.menu a { color: green !important; }
a.link  { color: navy; }
HTML
<nav id="nav" class="menu"><a class="link" href="#">Home</a></nav>
Show answer

Crimson. Both important declarations beat the normal one; between them, #nav a (1-0-1) is more specific than .menu a (0-1-1).

The rules applied
CSS
#nav a  { color: crimson !important; }
.menu a { color: green !important; }
a.link  { color: navy; }
HTML
<nav id="nav" class="menu"><a class="link" href="#">Home</a></nav>
Resultlive, in your browser
What’s happening
  1. Importance first: a.link is normal and is knocked out by both important declarations.
  2. The two important declarations tie on origin, have no inline style or layers, so specificity decides: 1-0-1 beats 0-1-1.
  3. Crimson. Order of appearance would only matter if their specificity were equal.
Open in topic →

When would you use !important?

Show answer

!important moves a declaration into a higher cascade tier, so it beats every normal declaration, including inline styles and ids; between important declarations the usual rules apply, and for origins the order reverses, so a user's important styles beat the author's. I use it sparingly for things that must always win: utility classes like .visually-hidden or .hidden, the [hidden] { display: none !important } reset, overriding third-party inline styles, and reduced-motion overrides. Using it to win a specificity fight in your own code just starts an arms race. Today I'd reach for cascade layers or :where() to control priority instead.

Open in topic →

Layered or not?

CSS
@layer components { #hero .title { color: crimson; } }
.title { color: green; }
HTML
<section id="hero"><h1 class="title">Hi</h1></section>

What colour is the heading?

Show answer

Green. The unlayered .title beats every layered declaration, whatever their specificity.

The rules applied
CSS
@layer components { #hero .title { color: crimson; } }
.title { color: green; }
HTML
<section id="hero"><h1 class="title">Hi</h1></section>
Resultlive, in your browser
What’s happening
  1. #hero .title is 1-1-0 but lives in the components layer; .title is 0-1-0 and unlayered.
  2. The layer step comes before specificity, and unlayered styles count as the last layer: green.
  3. This catches teams adopting layers gradually: old unlayered CSS beats everything in the new layers. Wrap legacy CSS in its own layer (for example with @import url(legacy.css) layer(legacy)) to put it back in its place.
Open in topic →

What are cascade layers for?

Show answer

@layer lets you group CSS into named layers and declare their order, and in the cascade the layer comparison happens before specificity, so a rule in a later layer wins even against a more specific selector in an earlier one. Unlayered styles beat all layers for normal declarations, and for !important the order reverses, earlier layers winning. I declare the order once at the top, something like @layer reset, vendor, base, components, utilities;, import third-party CSS into a low layer with @import … layer(vendor), and that removes most of the need for high specificity or !important. They've been Baseline since 2022, and revert-layer lets a rule fall back to the previous layer.

Open in topic →

What colour is the link?

CSS
:is(nav, #footer) a { color: crimson; }
.menu a.active      { color: green; }
HTML
<nav class="menu"><a class="active" href="#">Home</a></nav>
Show answer

Crimson. :is(nav, #footer) a is 1-0-1, because :is() takes the specificity of #footer, even though the link matched through nav.

The rules applied
CSS
:is(nav, #footer) a { color: crimson; }
.menu a.active      { color: green; }
HTML
<nav class="menu"><a class="active" href="#" id="a">Home</a></nav>
Resultlive, in your browser
What’s happening
  1. .menu a.active is 0-2-1: two classes and one type.
  2. :is(nav, #footer) a takes its most specific argument, #footer, so it's 1-0-0 plus a: 1-0-1. There's no #footer on the page, but that doesn't matter.
  3. One id beats any number of classes: crimson. Rewriting it as :where(nav, #footer) a (0-0-1) would let .menu a.active win.
Open in topic →

:is() vs :where(), and what :has() is for

Show answer

:is() and :where() both match any element that matches one of their arguments, and both use forgiving parsing, so an unsupported argument doesn't break the rule. The difference is specificity: :is() takes its most specific argument's specificity, even when the element matched a weaker one, while :where() is always zero, which I use for resets and library defaults that should be easy to override. :not() excludes elements and also takes its strongest argument's specificity. :has() is the relational selector: it lets me style an element based on its descendants or following siblings, so a parent selector, a previous-sibling selector or a quantity query, and it's been in every major browser since late 2023.

Open in topic →

Which scope wins?

CSS
@scope (.page)  { .btn { color: crimson; } }
@scope (.modal) { .btn { color: green; } }
HTML
<div class="modal"><div class="page"><button class="btn">OK</button></div></div>
Show answer

Crimson. Specificity ties (0-1-0), and .page is the nearer scope root (1 hop) than .modal (2 hops). Source order never gets a say.

The rules applied
CSS
@scope (.page)  { .btn { color: crimson; } }
@scope (.modal) { .btn { color: green; } }
HTML
<div class="modal"><div class="page"><button class="btn" id="b">OK</button></div></div>
Resultlive, in your browser
What’s happening
  1. Both scoped rules match the button with .btn (0-1-0): specificity ties.
  2. Proximity: .page is the button's parent, 1 hop; .modal is 2 hops. Fewer hops wins.
  3. Crimson, even though the .modal rule comes later. Only if proximity also tied would order of appearance decide.
Open in topic →

What does @scope add over normal selectors?

Show answer

@scope (.root) to (.limit) applies rules only to elements inside the root and above the lower boundary, which gives components styles that don't leak out and don't reach into slotted content. It also adds scope proximity to the cascade, after specificity and before source order, so with nested themes the nearest scope root wins instead of whichever rule came last. The root selector adds no specificity, so scoped rules stay easy to override, and :scope targets the root itself. It's been in all three engines only since Firefox 146 at the end of 2025, so for older browsers I'd still rely on CSS Modules or a naming convention and treat @scope as progressive enhancement.

Open in topic →

How tall is the wrapper?

CSS
.wrap { width: 300px; background: #f1f5f9; }
.out { position: absolute; width: 100px; height: 100px; }
.side { float: left; width: 80px; height: 120px; }
.in { height: 60px; }
HTML
<div class="wrap">
  <div class="out"></div>
  <div class="side"></div>
  <div class="in"></div>
</div>
Show answer

60px. Only .in is in normal flow. The absolutely positioned box and the float are both out of flow, so they don't add to the wrapper's height, even though they stick out below it.

CSS
.wrap { width: 300px; background: #f1f5f9; margin-bottom: 70px; }
.out { position: absolute; width: 100px; height: 100px; background: #fca5a5; }
.side { float: left; width: 80px; height: 120px; background: #bbf7d0; }
.in { height: 60px; background: #dbeafe; }
HTML
<div class="wrap">
  <div class="out">out</div>
  <div class="side">side</div>
  <div class="in">in</div>
</div>
Resultlive, in your browser
What’s happening
  1. .out is position: absolute with no offsets, so it stays at its static position (where it would have been: the top-left of .wrap) but takes up no space.
  2. .side is a float. Floats are out of flow for their parent's height too, so it hangs 60px below the wrapper.
  3. .in is the only in-flow child. Its block box starts at the very top of .wrap (block boxes run under floats; only line boxes move aside, see Floats and clearing), and its 60px is the wrapper's whole height.
  4. Painting order decides who's visible where they overlap: the positioned .out paints above the float, and the float paints above the in-flow block's background. elementFromPoint finds .out at the corner, .side just below it, and .in to the right.
  5. To make the wrapper contain the float, give it display: flow-root. Nothing makes it grow for an absolutely positioned child: that's the point of absolute positioning.
Open in topic →

What is normal flow?

Show answer

Normal flow is the default layout: block boxes stack in the block direction and each fills its container's width, while inline content is laid out in line boxes that wrap. Every in-flow box takes up space and pushes what follows, which is why changing one element's size reflows its siblings. Floats and absolute or fixed positioning take a box out of flow, so the content around it closes up and its parent no longer grows for it. Flex and grid containers don't take children out of flow; they replace block layout for their children with a different algorithm.

Open in topic →

Where does the box end up?

CSS
.box { position: relative; top: -10px; bottom: 50px; left: 20px; right: 20px; }
Show answer

10px up and 20px to the right of its normal position (in a left-to-right page), and it's still exactly its normal size.

CSS
.lane { width: 300px; height: 70px; padding-top: 20px; background: #f1f5f9; }
.box { position: relative; top: -10px; bottom: 50px; left: 20px; right: 20px; width: 120px; height: 30px; background: #c4b5fd; }
HTML
<div class="lane"><div class="box">box</div></div>
Resultlive, in your browser
What’s happening
  1. Negative offsets are allowed: top: -10px moves the box up. Its slot is 20px down (the lane's padding), so it paints 10px down.
  2. top and bottom are both set; top wins and bottom: 50px is ignored.
  3. left and right are both set; in LTR left wins, so the box moves 20px right.
  4. Its size doesn't change: unlike an absolutely positioned box, a relative box is never stretched by opposing offsets. It's still 120 × 30px.
Open in topic →

static vs relative

Show answer

static is the default: the box is in normal flow and offsets and z-index don't apply. relative keeps the box in flow, so it still takes up its normal space, and paints it shifted by top/left from that spot without moving anything else. Its main uses are its side effects: it makes the element positioned, so absolutely positioned children use it as their containing block, and so z-index works on it. If top and bottom conflict, top wins; for left/right, the start side wins.

Open in topic →

Where does the child end up?

CSS
.grand { position: relative; width: 300px; height: 140px; border: 4px solid; padding: 10px; }
.parent { margin: 20px; padding: 30px; }          /* static */
.child { position: absolute; bottom: 0; left: 0; width: 50px; height: 50px; }
HTML
<div class="grand"><div class="parent"><div class="child"></div></div></div>
Show answer

In the bottom-left corner of .grand's padding box: 4px in from .grand's left border edge and 4px up from its bottom border edge. .parent's margin and padding play no part, because .parent is static.

CSS
.grand { position: relative; width: 300px; height: 140px; border: 4px solid #93c5fd; padding: 10px; background: #eff6ff; }
.parent { margin: 20px; padding: 30px; background: #dbeafe; }
.child { position: absolute; bottom: 0; left: 0; width: 50px; height: 50px; background: #fca5a5; }
HTML
<div class="grand"><div class="parent">parent<div class="child"></div></div></div>
Resultlive, in your browser
What’s happening
  1. Walk up from .child looking for a positioned ancestor: .parent is static, so skip it; .grand is relative. .grand is the containing block.
  2. The containing block is .grand's padding box: inside its 4px border, but including its 10px padding. So left: 0 is 4px in from the outer edge, not 14px.
  3. bottom: 0 measures from the bottom of the same padding box: 4px above the outer bottom edge.
  4. .parent's 20px margin and 30px padding would only matter if .parent were positioned, or if the child had auto offsets (then its static position would be inside .parent's content box).
Open in topic →

What is the containing block?

Show answer

The containing block is the rectangle a box is sized and positioned against. For normal-flow (static, relative, sticky) boxes it's the content box of the nearest block container. For position: absolute it's the padding box of the nearest positioned ancestor, or the initial containing block if there is none, which is why we put position: relative on a parent: to say "measure from me". position: fixed uses the viewport, unless an ancestor has a transform, filter or similar, which then becomes the containing block. Percentages for width, left and right resolve against its width, and for height, top and bottom against its height.

Open in topic →

A "fixed" header that scrolls away

A header has position: fixed; top: 0, and it scrolls away with the content instead of staying put. Its only ancestors are body, html, and a wrapper div.app with transform: translateZ(0) that someone added "for performance". What's going on?

Show answer

.app's transform makes it the header's containing block, so the header is fixed to .app, not the viewport. It's positioned at .app's top and moves when .app moves, which, when the document scrolls, is exactly like an absolute element.

What’s happening
  1. The containing block of a fixed box is the viewport unless an ancestor has a transform (or filter, perspective, will-change: transform, contain: layout…) other than none.
  2. translateZ(0) is a transform, even though it moves nothing. It was a common hack to force a GPU layer, and it silently changes layout rules.
  3. So top: 0 now means "the top of .app's padding box", and when the page scrolls, .app scrolls and takes the header with it (the demo above shows the same capture with transform: translateX(0)).
  4. Fix: remove the transform from the ancestor (or move it to an element that doesn't contain the header), or move the header out of .app.
Open in topic →

How does position: fixed work?

Show answer

A fixed element is taken out of flow and positioned relative to the viewport, so it stays in place when the page or any scroll container scrolls; it always forms a stacking context. The gotcha is that the viewport is only the containing block if no ancestor has a transform, filter, perspective, will-change: transform or contain: layout; any of those turns the fixed element into what is effectively an absolute element inside that ancestor. For modals and menus I'd prefer <dialog> or the popover API, which use the top layer and avoid both z-index and containing-block problems.

Open in topic →

Where is the header?

A scroller is 150px tall. Its first section is 200px tall and starts with a 30px header that has position: sticky; top: 10px. The scroller is scrolled down by 175px. Where is the header's top, relative to the scroller's top?

Show answer

At −5px. It wants to stick at 10px, but its section's bottom edge is only 25px from the top, and the header can't leave its section.

CSS
.scroller { width: 300px; height: 150px; overflow: auto; background: #f8fafc; }
.section { height: 200px; background: #eff6ff; }
.section + .section { background: #f0fdf4; }
.head { position: sticky; top: 10px; height: 30px; background: #93c5fd; }
HTML
<div class="scroller">
  <div class="section"><div class="head">Section 1</div></div>
  <div class="section"><div class="head">Section 2</div></div>
</div>
Resultlive, in your browser
What’s happening
  1. In normal flow the header would be at 0 − 175 = −175px, way above the scrollport.
  2. Sticky clamps it to the threshold: it wants to be at top: 10px.
  3. But it must stay inside its containing block, the section, whose bottom edge is at 200 − 175 = 25px. The header's bottom can't go past 25px, so its top is at most 25 − 30 = −5px.
  4. The smaller of "where it wants to stick" (10) and "how far its rail allows" (−5) wins: −5px. Scroll 20px less and it would be at the full 10px.
Open in topic →

How does position: sticky work, and why might it not?

Show answer

A sticky element is in normal flow like a relative one, but once scrolling would move it past its threshold (say top: 0) relative to its nearest scroll container, it sticks there, and it only stays stuck while its containing block, usually the parent, is still in view. It doesn't work without a threshold; it attaches to the nearest ancestor with overflow other than visible/clip, so an overflow: hidden wrapper breaks it (overflow: clip doesn't); and it needs room, so a flex or grid item stretched to its parent's full height can't move (align-self: start fixes that). It also creates a stacking context, so headers usually need a z-index and a background.

Open in topic →

Which one is on top?

A site header has position: sticky; top: 0; z-index: 10. Inside it is a dropdown menu with position: absolute; z-index: 9999. The page content below is a <main> with position: relative; z-index: 20. The dropdown opens over <main>. Which is on top?

Show answer

<main> is on top. The header is a stacking context at level 10, so the dropdown's 9999 only counts inside the header; <main> at 20 beats the header's 10.

CSS
.header { position: sticky; top: 0; z-index: 10; height: 40px; background: #93c5fd; }
.menu { position: absolute; z-index: 9999; top: 30px; left: 20px; width: 160px; height: 80px; background: #fde68a; }
main { position: relative; z-index: 20; display: block; height: 100px; background: #f0fdf4; }
HTML
<header class="header">header<div class="menu">menu (z 9999)</div></header>
<main>main (z 20)</main>
Resultlive, in your browser
What’s happening
  1. position: sticky always forms a stacking context, and z-index: 10 places that context at level 10 in the root.
  2. <main> is positioned with z-index: 20, a sibling of the header in the root context. 20 > 10, so <main> paints above the header and everything inside it.
  3. The menu wins inside its own folder (it covers the header's background at 35px) but loses where it hangs over <main> (at 60px).
  4. Fixes: raise the header above <main> (z-index: 30), drop <main>'s z-index if it doesn't need one, or put the menu in the top layer with the popover API so no z-index is involved.
Open in topic →

Explain z-index and stacking contexts

Show answer

z-index reorders overlapping boxes, but only boxes in the same stacking context are compared. A stacking context is a group the browser paints as one unit; it's created by the root, by positioned elements with a non-auto z-index, by fixed and sticky elements, and as a side effect by things like opacity below 1, transform, filter and isolation: isolate. So a child with z-index: 9999 can never rise above an element that beats its ancestor context, and the fix is to change the ancestor, not to add nines. Within a context the order is: background, negative z-index, in-flow blocks, floats, inline content, positioned auto/0, then positive z-index; I use isolation: isolate to create a context deliberately.

Open in topic →

How tall is the container?

CSS
.c { width: 300px; }
.a { float: left; width: 100px; height: 50px; }
.b { float: right; width: 100px; height: 70px; }
.p { height: 20px; }
HTML
<div class="c"><div class="a"></div><div class="b"></div><div class="p"></div></div>

What if you add display: flow-root to .c?

Show answer

20px, the height of .p, the only in-flow child. With display: flow-root it's 70px, the bottom of the taller float.

CSS
.c { width: 300px; background: #f1f5f9; margin-bottom: 80px; }
.a { float: left; width: 100px; height: 50px; background: #c7d2fe; }
.b { float: right; width: 100px; height: 70px; background: #fbcfe8; }
.p { height: 20px; background: #bbf7d0; }
HTML
<div class="c" id="plain"><div class="a"></div><div class="b"></div><div class="p"></div></div>
<div class="c" id="root" style="display: flow-root"><div class="a"></div><div class="b"></div><div class="p"></div></div>
Resultlive, in your browser
What’s happening
  1. Both floats are out of flow, so without a BFC they don't add to .c's height. .p is in flow and starts at the top, under the floats: .c is 20px.
  2. display: flow-root makes .c a block formatting context, and a BFC's height includes its floats' bottom margin edges. The taller float ends at 70px, so .c grows to 70px.
  3. .p still starts at 0 in both cases: making .c a BFC doesn't push .p below the floats; only clear would.
Open in topic →

How do floats work, and what is a clearfix?

Show answer

A float is taken out of flow and moved to the left or right of its container, and the line boxes of following content shorten to wrap around it, while their block boxes still run underneath. Because it's out of flow, a parent containing only floats collapses to zero height. clear pushes an element below earlier floats, and the clearfix used that with an ::after pseudo-element to make the parent contain its floats; today display: flow-root does it directly by creating a block formatting context. I use floats only to wrap text around media, and flex or grid for layout.

Open in topic →

Why isn't this centred vertically?

CSS
.parent { height: 300px; }
.child { width: 200px; height: 100px; margin: auto; }
Show answer

Because .parent is a plain block. In block layout vertical auto margins compute to 0, so the child is centred horizontally only. Make the parent display: flex (or grid), or add align-content: center to the parent.

What’s happening
  1. margin: auto sets all four margins to auto.
  2. Horizontally, a block with a fixed width splits the spare space between auto left and right margins: centred.
  3. Vertically, block layout doesn't distribute spare height to margins; auto top and bottom margins become 0, so the child sits at the top (the demo above measures margin-top: 0px).
  4. In a flex or grid container, auto margins absorb free space on both axes, so the same margin: auto centres both ways. Or keep block layout and use align-content: center on the parent (Baseline 2024).
Open in topic →

How do you centre a div?

Show answer

For both axes I use flexbox, display: flex; justify-content: center; align-items: center, or grid with place-items: center, or just margin: auto on the child of a flex container, which also stays safe when the child is larger than the container. For a block that only needs horizontal centring, give it a width and margin-inline: auto; for inline content, text-align: center. For overlays, an absolutely positioned box with inset: 0; margin: auto and a size, or top: 50%; left: 50%; transform: translate(-50%, -50%) when the size is unknown. And since 2024 align-content: center works on plain blocks too.

Open in topic →

What is CSS anchor positioning?

Show answer

It lets you position an absolutely or fixed positioned element relative to another element, the anchor, instead of its containing block: the anchor gets anchor-name: --x, the popup gets position-anchor: --x and either insets like top: anchor(bottom) or a position-area cell such as top center. position-try-fallbacks: flip-block lets the browser flip it when it would overflow, and anchor-size() sizes it from the anchor. Combined with the popover API, which gives an implicit anchor and the top layer, it replaces most of what Popper or Floating UI did with JavaScript. It's Baseline 2026, newly available since Firefox shipped it in January 2026, so I'd still wrap it in @supports with a simple fallback for older browsers.

Open in topic →

Where does the item go?

CSS
.box { display: flex; flex-direction: column; justify-content: center; align-items: flex-end;
       width: 300px; height: 200px; }
.item { width: 60px; height: 40px; }
Show answer

Vertically centred and against the right edge: its top-left corner is at (240, 80). In a column, justify-content works vertically and align-items horizontally.

CSS
.box { display: flex; flex-direction: column; justify-content: center; align-items: flex-end; width: 300px; height: 200px; background: #f1f5f9; }
.item { width: 60px; height: 40px; background: #93c5fd; }
HTML
<div class="box"><div class="item"></div></div>
Resultlive, in your browser
What’s happening
  1. flex-direction: column makes the main axis vertical.
  2. justify-content: center shares the free main-axis space equally: 200 − 40 = 160px, 80px above and 80px below, so the top is at 80px.
  3. align-items: flex-end aligns on the cross axis, now horizontal, to the cross-end edge: the right. 300 − 60 = 240px from the left.
  4. If you swapped the direction back to row, the same two declarations would put the item at (120, 160): centred horizontally, at the bottom.
Open in topic →

Main axis and cross axis

Show answer

A flex container lays out its direct children along one axis, the main axis, set by flex-direction; the cross axis is perpendicular to it. justify-content distributes space along the main axis and align-items/align-self position items on the cross axis, so in a column they effectively swap horizontal and vertical. By default items don't wrap and they stretch across the cross axis, which is where free equal-height columns come from. A row follows the inline direction, so it starts on the right in RTL, and the reverse values change only the visual order, not the DOM or tab order.

Open in topic →

Container or item?

Which of these do nothing where they're written? .item { justify-content: center }, .list { flex: 1 } (on a flex container whose parent is a block), .item { align-self: center }, .list { align-items: center }.

Show answer

The first two. justify-content is a container property, so on an item it only affects that item's own children (if it's a flex container itself). flex is an item property, so it does nothing on an element whose parent isn't a flex container. align-self belongs on items and align-items on containers, so those two work.

What’s happening
  1. Ask of every property: does it describe how my children are laid out (container), or how I behave inside my parent's flex layout (item)?
  2. justify-content, align-items, align-content, flex-direction, flex-wrap, gap are about children: container.
  3. flex, flex-grow, flex-shrink, flex-basis, align-self, order are about the element itself: item, and only meaningful if the parent is a flex container.
  4. An element can be both at once (a flex item that is also a flex container), which is how nested flex layouts work.
Open in topic →

flex vs inline-flex, and container vs item properties

Show answer

display: flex creates a block-level flex container and inline-flex an inline-level one that shrinks to its content and sits in a line; inside, both lay items out the same way. The container controls direction, wrapping, justify-content, align-items, align-content and gap; the items control their own flex (grow, shrink, basis), align-self and order. order only changes the visual order, so tab and screen-reader order no longer match what you see, and I avoid it for interactive content.

Open in topic →

Where does each item start?

A 400px flex container has four 50px items and justify-content: space-around. Where does each item start?

Show answer

At 25, 125, 225 and 325px.

CSS
.track { display: flex; justify-content: space-around; width: 400px; height: 30px; background: #f1f5f9; }
.track i { flex: none; width: 50px; background: #93c5fd; }
HTML
<div class="track"><i></i><i></i><i></i><i></i></div>
Resultlive, in your browser
What’s happening
  1. The items take 4 × 50 = 200px, so the free space is 400 − 200 = 200px.
  2. space-around gives each item an equal share, 200 / 4 = 50px, split half before and half after it: 25px on each side.
  3. The first item starts at 25px. Between neighbours there are 25 + 25 = 50px, so each next item starts 50 + 50 = 100px later: 125, 225, 325.
  4. The last item ends at 375px, leaving 25px at the end: half-size gaps at the edges are what distinguishes space-around from space-evenly.
Open in topic →

justify-content vs align-items vs align-content

Show answer

All three distribute free space. justify-content works on the main axis, distributing what's left after the items are sized: start, centre, end, or between and around them. align-items positions each item within its line on the cross axis, with stretch as the effective default, which only stretches items with an auto cross size; align-self overrides it per item. align-content spaces the lines themselves in a wrapping container and does nothing in a single-line one. justify-items/justify-self don't apply in flexbox; auto margins do that job.

Open in topic →

How wide is each item?

CSS
.c { display: flex; gap: 20px; width: 500px; }
.a { flex: 1 1 100px; }
.b { flex: 2 1 100px; }
Show answer

.a ≈ 193.33px and .b ≈ 286.67px.

CSS
.c { display: flex; gap: 20px; width: 500px; height: 30px; background: #f1f5f9; }
.a { flex: 1 1 100px; background: #93c5fd; }
.b { flex: 2 1 100px; background: #c4b5fd; }
HTML
<div class="c"><div class="a">a</div><div class="b">b</div></div>
Resultlive, in your browser
What’s happening
  1. Bases: 100 + 100 = 200px. Don't forget the gap: free space = 500 − 200 − 20 = 280px.
  2. Grow factors 1 and 2, total 3: one share is 280 / 3 ≈ 93.33px.
  3. .a = 100 + 93.33 ≈ 193.33px, .b = 100 + 186.67 ≈ 286.67px. Measured to within 0.1px.
  4. The common mistake is to forget the gap (giving 200 and 300) or to split the whole 500px 1 : 2 (giving 166.67 and 333.33), which would only be right with zero bases and no gap.
Open in topic →

How does flexbox decide item sizes?

Show answer

Each item starts at its flex basis: flex-basis, or its width if the basis is auto, or its content size. The container subtracts the bases, margins and gaps from its size; positive free space is shared in proportion to flex-grow, and negative free space is removed in proportion to flex-shrink multiplied by the basis, so bigger items shrink more. Any item that hits a min or max size is frozen there and the rest is redistributed. So with bases 100/150/50, grow 1/2/1 and 600px, the 300px surplus splits 75/150/75, giving 175, 300 and 125.

Open in topic →

flex-grow: 1 vs flex: 1

Two items in a 600px row contain 40px and 160px of content. Case A gives both flex-grow: 1; case B gives both flex: 1. How wide are they?

Show answer

A: 240px and 360px. B: 300px and 300px. flex-grow: 1 alone leaves flex-basis: auto, so it behaves like flex: auto; flex: 1 also sets the basis to 0%.

CSS
.c { display: flex; width: 600px; margin-bottom: 8px; background: #f1f5f9; }
.c > div { background: #c4b5fd; box-shadow: inset 0 0 0 1px #f1f5f9; }
.c i { display: inline-block; vertical-align: top; height: 30px; background: #5b21b6; }
.a > div { flex-grow: 1; }
.b > div { flex: 1; }
HTML
<div class="c a"><div><i style="width: 40px"></i></div><div><i style="width: 160px"></i></div></div>
<div class="c b"><div><i style="width: 40px"></i></div><div><i style="width: 160px"></i></div></div>
Resultlive, in your browser
What’s happening
  1. Case A: only flex-grow changes; flex-basis stays auto, so the bases are the content sizes, 40 and 160px. Free space is 600 − 200 = 400px, 200px each: 240 and 360px.
  2. Case B: flex: 1 is 1 1 0%, so both bases are 0 and all 600px are split equally: 300 and 300px.
  3. So "make them equal" needs flex: 1 (or flex-basis: 0 explicitly), not just flex-grow: 1.
  4. Even flex: 1 columns stop being equal when one contains something wider than its share that can't shrink, like a long URL: the automatic minimum size kicks in (see Why flex items overflow).
Open in topic →

What does flex: 1 mean?

Show answer

flex: 1 is shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0%. Because the basis is zero, the whole container is shared out by the grow factors, so flex: 1 siblings end up equal regardless of content, whereas flex: auto (1 1 auto) starts from the content size and only shares the leftover. The default is 0 1 auto, and flex: none is 0 0 auto for things that must not resize. Two caveats: items still won't shrink below their content's minimum width unless you set min-width: 0, and in a column with no definite height the 0% basis behaves like content.

Open in topic →

How many items per row?

Items are flex: 0 0 150px in a 500px wrapping container. How many fit on a row with gap: 20px? With gap: 30px?

Show answer

Three with a 20px gap, two with a 30px gap.

CSS
.c { display: flex; flex-wrap: wrap; width: 500px; background: #f1f5f9; margin-bottom: 10px; }
.c > div { flex: 0 0 150px; height: 20px; background: #93c5fd; }
HTML
<div class="c" id="g20" style="gap: 20px"><div></div><div></div><div></div><div></div></div>
<div class="c" id="g30" style="gap: 30px"><div></div><div></div><div></div><div></div></div>
Resultlive, in your browser
What’s happening
  1. n items fit if n × 150 + (n − 1) × gap ≤ 500.
  2. Gap 20px: three items need 450 + 40 = 490px ≤ 500 → 3 per row (a fourth would need 660px).
  3. Gap 30px: three items need 450 + 60 = 510px > 500 → only 2 per row.
  4. Gaps count when deciding where to wrap, which is why adding a bigger gap can suddenly drop a column on the same screen.
Open in topic →

How does flex-wrap work?

Show answer

With flex-wrap: wrap, items are put on a line by their hypothetical size, the flex basis clamped by min and max, until the next one won't fit, including the gaps; then each line is flexed independently, distributing its own free space. That's why items on a short last line grow wider than the ones above, and if you want aligned columns, grid with auto-fill and minmax() is the right tool. gap adds space between items and lines only, never at the edges, and replaced the negative-margin hack; align-content then spaces the lines on the cross axis.

Open in topic →

Why is the page wider than the phone?

A chat layout: .layout { display: flex }, .sidebar { width: 80px; flex: none }, .messages { flex: 1 }. One message contains a 600px code block (<pre>, with overflow-x: auto on the pre). On a 360px phone the whole page scrolls sideways. Why, and what's the one-line fix?

Show answer

.messages has min-width: auto, so it won't shrink below the <pre>'s 600px min-content width. Add min-width: 0 to .messages; then the pre is constrained to the column and its own overflow-x: auto scrolls it.

What’s happening
  1. flex: 1 means "share the space", but flex items also have an automatic minimum width: their min-content width, unless their overflow isn't visible.
  2. A <pre> doesn't wrap, so the message column's min-content width is about the code block's 600px. .messages becomes ~600px, the row becomes ~680px, and the page overflows the 360px viewport.
  3. The pre's overflow-x: auto never kicks in, because the pre is given all the width it wants; nothing is constraining it.
  4. min-width: 0 on .messages lets it shrink to 360 − 80 = 280px; the pre is now 280px wide and scrolls inside. overflow: hidden on .messages would also work, but would clip things like focus rings and shadows.
Open in topic →

Why do flex items overflow their container?

Show answer

Flex items default to min-width: auto, which for a flex item means a content-based minimum, roughly its min-content width, so an item containing a long word, a pre or a nowrap title won't shrink below it, even with flex: 1, and it pushes the layout wider. The fix is min-width: 0 on that item, or an overflow other than visible, which removes the automatic minimum, so the content overflows inside the item and can be scrolled, clipped or truncated. In columns it's the same with min-height: auto, the usual reason a nested scroll panel grows instead of scrolling. Text ellipsis inside flex needs min-width: 0 on the flex item, not just on the text.

Open in topic →

Show me some flexbox layouts you use often

Show answer

A navbar is a row with align-items: center and margin-left: auto on the first right-hand item, which acts as a spring pushing that group to the end. A sticky footer is a column with min-height: 100dvh and flex: 1 on main. Card grids get equal heights for free from stretch, and making each card a column with margin-top: auto on the button lines the buttons up. Input-plus-button rows use flex: 1; min-width: 0 on the input and flex: none on the button, and a sidebar with a flex basis and flex-wrap: wrap drops under the content on narrow screens without a media query. When I need rows and columns to line up, I switch to grid (see Grid or flexbox?).

Open in topic →

Count the lines

A grid has grid-template-columns: repeat(4, 1fr) and grid-template-rows: 100px 100px 100px. How many column lines and row lines are there, and what is line -1 in each direction?

Show answer

Five column lines and four row lines. Column line -1 is line 5, row line -1 is line 4.

What’s happening
  1. Lines bound tracks, so there's always one more line than tracks: 4 columns → lines 1 to 5, 3 rows → lines 1 to 4.
  2. Negative numbers count backwards from the end of the explicit grid: -1 is the last line (5 for columns, 4 for rows), -2 is the one before it, and so on.
  3. So grid-column: 1 / -1 means 1 / 5, which spans all four columns. Gaps never add lines; they only widen the existing ones.
Open in topic →

Explain the grid terminology

Show answer

A grid container defines tracks with grid-template-columns and grid-template-rows. The tracks are separated by numbered lines (1 to n+1 from the start, or -1 backwards from the end), and lines are the coordinates you place items with. A cell is one row crossed with one column; a grid area is any rectangle of cells, and each item occupies one area. Gaps are gutters between tracks, not tracks. Only direct children of the container are items, which is why subgrid and display: contents exist.

Open in topic →

Work out the fr size

A grid is 500px wide with grid-template-columns: 200px 1fr 1fr and gap: 10px. How wide is each 1fr column?

Show answer

140px each.

The quiz grid, measured
CSS
.grid { display: grid; width: 500px; grid-template-columns: 200px 1fr 1fr; gap: 10px; }
.grid > div { height: 30px; background: #fef3c7; color: #78350f; }
HTML
<div class="grid"><div>200px</div><div>1fr</div><div>1fr</div></div>
Resultlive, in your browser
What’s happening
  1. Take out everything that isn't flexible: the 200px track and two 10px gaps → 500 − 200 − 20 = 280px left.
  2. There are 2fr in total, so 1fr = 280 / 2 = 140px, which is what the browser measures.
  3. Percentages would get this wrong: 200px 1fr 1fr can't be written as percentages without doing the gap arithmetic by hand.
Open in topic →

What does fr mean?

Show answer

fr is a fraction of the free space in the grid container: the browser sizes fixed and content-based tracks and the gaps first, then divides what's left between the fr tracks in proportion. Unlike percentages it accounts for gaps, so tracks never overflow because of gutters. One subtlety: 1fr is minmax(auto, 1fr), so an fr track won't shrink below its content's minimum width. When equal columns must stay equal regardless of content, I write minmax(0, 1fr).

Open in topic →

How many columns at 700px?

A page has a <div> with display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px, inside a body with 12px margins. The viewport is 700px wide and there are three items. How many columns are there, and how wide is each item? What changes with auto-fit?

Show answer

Four columns of 161.5px, with the fourth one empty. With auto-fit the empty track collapses and the three items are 218.7px each.

What’s happening
  1. Available width: 700 − 24 = 676px.
  2. Count from the minimum: floor((676 + 10) / (150 + 10)) = floor(4.29) = 4 tracks.
  3. Stretch: four tracks and three gaps → (676 − 30) / 4 = 161.5px each. The main example's test measures exactly this at 700px ("161.5px 161.5px 161.5px 161.5px").
  4. With auto-fit, the fourth track has no item, so it collapses to 0 along with its gap: (676 − 20) / 3 = 218.67px, measured as 218.7px.
Open in topic →

auto-fill vs auto-fit

Show answer

Both create as many tracks as fit, counted from the track's minimum size, and both are usually written as repeat(auto-fill, minmax(150px, 1fr)) for a responsive grid without media queries. They only differ when there are fewer items than tracks: auto-fill keeps the empty tracks, so items keep their column width; auto-fit collapses the empty tracks to zero, so the items stretch to fill the row. I use auto-fill when cards should stay a consistent size and auto-fit when a few items should spread out. For narrow containers I write the minimum as min(150px, 100%) so a single column can't overflow.

Open in topic →

Backwards lines

In a four-column grid, an item has grid-column: 4 / 2. Where does it go?

Show answer

It covers columns 2 and 3: from line 2 to line 4.

Start after end
CSS
.grid { display: grid; grid-template-columns: repeat(4, 50px); }
.grid > div { height: 30px; background: #e2e8f0; }
.grid > .x { grid-column: 4 / 2; background: #fca5a5; }
HTML
<div class="grid"><div class="x">4 / 2</div></div>
Resultlive, in your browser
What’s happening
  1. When the start line comes after the end line, the grid placement algorithm swaps them, so 4 / 2 is treated as 2 / 4.
  2. The item starts at line 2 (50px in) and is two tracks wide (100px), measured.
  3. The computed grid-column-start still says 4: the swap is part of placement, not a rewrite of your value. If start and end are the same line, the end is dropped instead and the item spans one track.
Open in topic →

How do you place a grid item?

Show answer

Items are placed by lines, not cells: grid-column: 2 / 4 means from column line 2 to column line 4, span 2 covers two tracks from wherever the item starts, and negative numbers count from the end of the explicit grid, so 1 / -1 is full width. grid-area is the four-value shorthand in the order row-start, column-start, row-end, column-end. Lines can be named, and an x-start/x-end pair lets you write grid-column: x, which is how the full-bleed layout works. Items can overlap and z-index works without positioning. The caveat is accessibility: placement changes the visual order but not the DOM order that keyboards and screen readers follow.

Open in topic →

Is this map valid?

CSS
grid-template-areas:
  "nav header header"
  "nav main"
  "nav footer footer";

What happens?

Show answer

The declaration is invalid and ignored, because row 2 has two cells while rows 1 and 3 have three.

The quiz map, measured
CSS
.g {
  display: grid;
  grid-template-areas:
    "nav header header"
    "nav main"
    "nav footer footer";
}
.g2 {
  display: grid;
  grid-template-areas:
    "nav header header"
    "nav main   main"
    "nav footer footer";
}
.g, .g2 { margin-bottom: 10px; outline: 2px dashed #94a3b8; }
.g > *, .g2 > * { padding: 2px 6px; background: #e0e7ff; }
nav { grid-area: nav; background: #dcfce7 !important; }
header { grid-area: header; }
main { grid-area: main; background: #fef3c7 !important; }
footer { grid-area: footer; }
HTML
<div class="g"><nav>nav</nav><header>header</header><main>main</main><footer>footer</footer></div>
<div class="g2"><nav>nav</nav><header>header</header><main>main</main><footer>footer</footer></div>
Resultlive, in your browser
What’s happening
  1. Every string must have the same number of cells. Row 2 has nav main (two), rows 1 and 3 have three.
  2. So the whole declaration fails to parse and is dropped: the computed value is none. The items still say grid-area: nav, header and so on, but no lines with those names exist. The spec's rule for a missing line name is to treat every implicit line as having it, so each item is placed one track past the explicit grid: all four land in the same cell, implicit column 2, row 2, on top of each other (measured: same position; the first column and row are empty tracks). On screen you see only the last item, footer, in the dashed box.
  3. The fix is "nav main main". Then nav is a valid 1 × 3 rectangle down the left and main a 2 × 1 rectangle in row 2.
  4. DevTools' Styles pane shows a rejected declaration struck through, which is the fastest way to catch this.
Open in topic →

When do you use grid-template-areas?

Show answer

For page-level and component layouts with a handful of named regions: header, nav, main, sidebar, footer. The map is readable, and responsive changes only redraw the map in a media query while items keep their grid-area names. The rules are strict: every row must have the same number of cells, and each area must be a rectangle, otherwise the whole declaration is dropped. For grids of many repeated items, like cards, I use repeat() and auto-placement instead, since you can't name every cell.

Open in topic →

How tall is the grid?

A grid has grid-template-columns: repeat(3, 1fr); grid-auto-rows: 50px; gap: 10px and ten empty divs. How tall is it?

Show answer

230px: four rows of 50px and three gaps.

The quiz grid, measured
CSS
.grid { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 50px; gap: 10px; }
.grid > div { background: #dbeafe; }
HTML
<div class="grid"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
Resultlive, in your browser
What’s happening
  1. Ten items in three columns need ceil(10 / 3) = 4 rows; the last row holds just item 10.
  2. None of the rows are declared, so all four are implicit and sized by grid-auto-rows: 50px.
  3. Height: 4 × 50 + 3 × 10 = 230px, measured. Empty items still occupy cells; it's the number of items, not their content, that decides the row count.
Open in topic →

What is the implicit grid?

Show answer

The explicit grid is the tracks you declare with grid-template-*. When items need more room (more items than cells, or an item placed beyond the last line), the browser creates implicit tracks sized by grid-auto-rows and grid-auto-columns. Auto-placement fills cells in grid-auto-flow order, rows by default, and dense lets later items backfill holes at the cost of visual order no longer matching DOM order. The usual pattern is to declare columns and let rows be implicit with grid-auto-rows: minmax(100px, auto). One gotcha: negative line numbers only count the explicit grid, so 1 / -1 doesn't span implicit rows.

Open in topic →

place-items vs place-content

Two 300px-wide grid containers each hold two items: one contains a 60px-wide box, the other a 120px-wide box. Neither container declares any columns. The first has place-items: center, the second place-content: center. Do the items end up the same width?

Show answer

No. With place-items: center each item is its own content width (60px and 120px), each centred. With place-content: center both items are 120px wide, because they stretch to fill a track sized by the widest one.

The quiz, measured
CSS
.grid { display: grid; width: 300px; height: 80px; margin-bottom: 10px; outline: 2px dashed #94a3b8; }
.items { place-items: center; }
.content { place-content: center; }
.grid > div { background: #bfdbfe; }
.w60 { width: 60px; height: 20px; }
.w120 { width: 120px; height: 20px; }
HTML
<div class="grid items"><div><div class="w60"></div></div><div><div class="w120"></div></div></div>
<div class="grid content"><div><div class="w60"></div></div><div><div class="w120"></div></div></div>
Resultlive, in your browser
What’s happening
  1. With no columns declared, each grid has one implicit auto column, and the two items stack in two implicit rows.
  2. place-items: center sets justify-items: center, so the items stop stretching and shrink to their content: 60px and 120px, each centred in a column that is still the full 300px (measured track: "300px"). They sit at 120px and 90px.
  3. place-content: center sets justify-content: center, which centres the track instead. An auto track that isn't stretched is as wide as its widest content, 120px, so it sits at 90px. The items keep the default justify-items: stretch and fill that track: both 120px wide.
  4. For one fixed-size child the two look identical, which is why both appear in "how do I centre a div" answers (see Centering things: every way). With several children, place-items centres each one, place-content centres the group.
Open in topic →

Explain justify vs align in grid

Show answer

justify-* is the inline axis (along a row) and align-* is the block axis (down a column), and that holds in grid whatever the content direction. At the container, *-content moves the tracks when they're smaller than the container, and *-items sets the default alignment of each item inside its own grid area; an item can override that with *-self. The default is stretch, except for items with a fixed size or an aspect ratio, like images, which align to the start. place-items: center is the shortest way to centre something in a grid, and the place-* shorthands take the block value first.

Open in topic →
InterviewCh 07 Subgrid

What problem does subgrid solve?

Show answer

A nested grid sizes its tracks only from its own content, so sibling cards in a grid can't align their insides: one long title pushes that card's body down and the rows look ragged. With grid-template-rows: subgrid, a card that spans several parent rows uses the parent's row tracks, and the parent sizes each row from the content of every card, so titles, bodies and footers line up across the whole row. It works for columns too, like aligning form labels and inputs across separate wrappers. Subgrid has been in every major engine since 2023 and is Baseline widely available from 2026; the fallback is simply an ordinary nested grid.

Open in topic →

Which one?

Pick grid or flexbox for each: (1) a header bar with a logo on the left and three links pushed to the right; (2) a photo gallery where every photo is the same width and rows line up; (3) a list of tags of different lengths that wraps onto several lines.

Show answer

(1) Flexbox, (2) grid, (3) flexbox.

What’s happening
  1. The header is a single line of content-sized items with space between groups: display: flex; align-items: center plus margin-left: auto on the first link (or justify-content: space-between with the links in a group). One dimension, sized by content.
  2. The gallery needs columns that line up across rows: repeat(auto-fill, minmax(200px, 1fr)) gives equal columns that adapt to the width, as measured in this topic's main example.
  3. Tags should each be as wide as their text and wrap like words: display: flex; flex-wrap: wrap; gap: 8px. In a grid every tag would be forced to a column width.
Open in topic →

Grid or flexbox?

Show answer

Flexbox is one-dimensional: it lays items along a line, sizes them from their content, and if they wrap, each line is independent. Grid is two-dimensional: I define rows and columns and place items into them, so they align both ways. So I use flexbox for components where content drives the layout (toolbars, nav bars, button groups, tags) and grid where the layout drives the content (page skeletons, galleries, forms with aligned labels, and subgrid for aligning sibling cards). In practice I use both on every page: grid for the macro layout, flexbox inside the components. They share gap and the alignment properties, so switching costs little.

Open in topic →

Exactly on the breakpoint

With the mobile-first CSS above (@media (min-width: 600px)), which layout does a viewport of exactly 600px get? And one of 599px?

Show answer

600px gets the two-column layout; 599px gets one column. min-width is inclusive.

The breakpoint, measured
CSS
.cards { display: grid; gap: 8px; }
@media (min-width: 600px) { .cards { grid-template-columns: 1fr 1fr; } }
.cards > div { height: 30px; background: #dcfce7; }
HTML
<div class="cards"><div></div><div></div></div>
Resultlive, in your browser
What’s happening
  1. min-width: 600px means "the viewport is at least 600px wide", so it's true at 600px itself: the two cards share a row.
  2. At 599px it's false and the cards stack.
  3. In the range syntax this is written (width >= 600px), which reads the way it behaves.
Open in topic →

What is mobile-first, and why?

Show answer

Mobile-first means the base CSS, outside any media query, is the small-screen layout, and min-width media queries add layout as the viewport grows. The base is usually simple, often just normal flow, so small devices get the least CSS and nothing has to be undone. Each breakpoint only adds rules, which keeps them from fighting, and it pushes you to prioritise content. I pick breakpoints where the content breaks, not at device widths, and increasingly I use intrinsic layouts and container queries so components adapt without page-level breakpoints at all.

Open in topic →

Why do you need the viewport meta tag?

Show answer

Without it, mobile browsers lay the page out in a virtual viewport around 980px wide and zoom out to fit, so media queries see 980px and never switch to the mobile layout, and text is tiny. width=device-width, initial-scale=1 sets the layout viewport to the device's width in CSS pixels at 100% zoom, so responsive CSS works. I never add user-scalable=no or maximum-scale=1: blocking zoom is an accessibility failure. If inputs trigger iOS's focus zoom, I give them a 16px font size instead.

Open in topic →

What colour at 600px?

With this CSS, what background does .box have at exactly 600px, and at 900px?

CSS
.box { background: blue; }
@media (min-width: 600px) { .box { background: green; } }
@media (max-width: 900px) { .box { background: red; } }
Show answer

Red at 600px, and red at 900px too.

The quiz, measured
CSS
.box { height: 30px; background: blue; }
@media (min-width: 600px) { .box { background: green; } }
@media (max-width: 900px) { .box { background: red; } }
HTML
<div class="box"></div>
Resultlive, in your browser
What’s happening
  1. At 600px both queries match (min-width and max-width are inclusive). Both rules have the same specificity (.box), so the later one in the source wins: red.
  2. At 900px, max-width: 900px still matches (inclusive), so again both match and red wins.
  3. Only from 901px is the second query false, and the box is green. Media queries don't add specificity, so when they overlap, order decides. Writing ranges that don't overlap (width < 900px) avoids the question entirely.
Open in topic →

How do media queries work?

Show answer

A media query wraps CSS in a condition about the viewport or the user's settings, and the browser re-evaluates it live. Width is the main one, and I use the range syntax, (width >= 600px), which is Baseline since 2023 and avoids the old overlap where max-width: 600px and min-width: 600px both match at 600. Beyond size there are hover and pointer for touch versus mouse, prefers-color-scheme, prefers-reduced-motion and orientation. Queries don't add specificity, so overlapping rules are decided by source order. And em in a media query is based on the browser's default font size, not the root font size.

Open in topic →

What does min() give?

A card has width: min(90%, 400px). Its container is 300px wide on a phone and 1000px on a desktop. How wide is the card in each?

Show answer

270px on the phone and 400px on the desktop.

What’s happening
  1. min() returns the smaller of its arguments, resolved against the container at layout time.
  2. Phone: 90% of 300px is 270px, smaller than 400px → 270px.
  3. Desktop: 90% of 1000px is 900px, larger than 400px → 400px. The centred-column demo above measures the same mechanism with min(100%, 500px).
Open in topic →

How do you make a layout responsive without media queries?

Show answer

I let the layout adapt to its container instead of switching at viewport breakpoints. Flexbox with flex-wrap and a flex-basis wraps items when they no longer fit, and the grid pattern repeat(auto-fill, minmax(min(200px, 100%), 1fr)) gives as many columns as fit. min(), max() and clamp() handle widths and spacing: width: min(100%, 60rem) for a centred column, padding: max(1rem, 4vw), clamp() for type. Because these respond to the container, a component works in a sidebar or the main column unchanged, and I keep media queries and container queries for real changes of arrangement.

Open in topic →

Work out the size

With font-size: clamp(1rem, 0.5rem + 2vw, 2rem) and the default 16px root, what's the font size at a 1000px viewport? At 300px?

Show answer

28px at 1000px, 16px at 300px.

What’s happening
  1. At 1000px: 0.5rem + 2vw = 8px + 20px = 28px, which is between 16px and 32px, so it's used as is. The main example's test measures 28px at 1000px.
  2. At 300px: 8 + 6 = 14px, below the 16px minimum, so it's clamped up to 16px.
Open in topic →

How does fluid typography with clamp() work?

Show answer

clamp(min, preferred, max) returns the preferred value limited to the range. For type, the preferred value is a linear function of the viewport, like 0.5rem + 2vw, so the size ramps smoothly between two viewport widths and stays flat outside them, with no breakpoints. I derive the slope and intercept from the sizes I want at two widths. I keep a rem term and rem limits so the text still respects the user's font-size setting and browser zoom; pure vw text ignores both and can fail WCAG's resize-text criterion. For components I use cqi so the type scales with the container instead of the window.

Open in topic →

Media or container?

A card sits in a 380px sidebar on a viewport 640px wide. Its CSS has @media (min-width: 600px) { .card { border-color: red; } } and @container (min-width: 400px) { .card { background: yellow; } }, and the sidebar has container-type: inline-size. Is the card red-bordered, yellow, both or neither?

Show answer

Red-bordered but not yellow: the media query sees the 640px viewport, the container query sees the 380px sidebar.

The quiz, measured
CSS
.sidebar { container-type: inline-size; width: 380px; }
.card { border: 4px solid #94a3b8; background: #fff; height: 30px; }
@media (min-width: 600px) { .card { border-color: red; } }
@container (min-width: 400px) { .card { background: yellow; } }
HTML
<div class="sidebar"><div class="card"></div></div>
Resultlive, in your browser
What’s happening
  1. @media (min-width: 600px) asks about the viewport, 640px in the test: true, so the border is red.
  2. @container (min-width: 400px) asks about the card's nearest container, the 380px sidebar: false, so the background stays white.
  3. That's the whole difference: the card in the sidebar should usually get its narrow layout even on a big screen, which only a container query can express.
Open in topic →

Media queries vs container queries

Show answer

Media queries respond to the viewport and the user's settings, so I use them for page-level layout and for preferences like dark mode or reduced motion. Container queries respond to the size of an ancestor marked with container-type: inline-size, so a component adapts to the space it's actually given, whether that's a sidebar or the main column. The container can't be the element you style, and because of size containment its width mustn't depend on its content, or it collapses to zero. They come with cqi-style units for component-relative sizing, and size queries have been Baseline since 2023. Style queries on custom properties reached all engines in 2026.

Open in topic →

Which file?

<img srcset="/demo/hero-480.jpg 480w, /demo/hero-960.jpg 960w" sizes="(min-width: 800px) 50vw, 100vw" src="/demo/hero-480.jpg"> at a viewport of 360px and of 1000px, both at a pixel ratio of 1. Which file is loaded in each?

Show answer

hero-480.jpg at 360px, and hero-960.jpg at 1000px.

The quiz, measured
CSS
img { display: block; width: 100%; height: 60px; background: #e0f2fe; }
@media (min-width: 800px) { img { width: 50%; } }
HTML
<img alt="hero" srcset="/demo/hero-480.jpg 480w, /demo/hero-960.jpg 960w" sizes="(min-width: 800px) 50vw, 100vw" src="/demo/hero-480.jpg">
Resultlive, in your browser
What’s happening
  1. At 360px, (min-width: 800px) is false, so the slot is 100vw = 360px. hero-480.jpg covers 360 pixels → chosen.
  2. At 1000px the slot is 50vw = 500px. hero-480.jpg would be 480 pixels for a 500px slot, slightly too few, so Chrome takes hero-960.jpg.
  3. On a 2x screen at 1000px it would need 1000 pixels and also takes hero-960.jpg (the largest available; measured in emulation, see the table above).
Open in topic →

How do responsive images work?

Show answer

For the same image at different resolutions I use srcset with width descriptors and a sizes attribute describing the display width, because the browser picks a file before CSS is loaded; it multiplies the slot width by the pixel ratio and chooses, and it's allowed to factor in cache and network. Fixed-size images just need 1x/2x density descriptors. For art direction or format fallback I use <picture>: the first <source> whose media and type match is used, and the inner <img> is required, renders the result and carries alt. I always set width and height to prevent layout shift, and for lazy images sizes="auto" lets the browser work out the slot itself where it's supported.

Open in topic →

Why does the button disappear?

A landing page has .hero { height: 100vh; display: flex; flex-direction: column; justify-content: flex-end; } with a "Get started" button at the bottom. On desktop it's perfect. On phones, people say the button isn't there until they scroll. Why, and what's the fix?

Show answer

100vh is the large viewport, measured with the browser UI hidden. When the page loads, the UI is showing, so the hero is taller than the visible area and its bottom edge, with the button, is under the toolbar. Use min-height: 100svh (with min-height: 100vh before it as a fallback).

What’s happening
  1. On page load the address bar and toolbar are visible, so the visible height is the small viewport.
  2. 100vh equals 100lvh, the height with the UI retracted, which is larger by the height of the browser UI. The hero overflows the visible area by that much.
  3. justify-content: flex-end puts the button at the hero's bottom edge, which is exactly the part that's hidden.
  4. 100svh is the small viewport, so the hero fits on load and the button is visible. 100dvh would also fit on load but would resize as the user scrolls. min-height instead of height lets the hero grow if its content needs more room on a short screen.
Open in topic →

vh vs svh, lvh and dvh

Show answer

On mobile the browser UI retracts as you scroll, so there are two viewport heights. lvh is the large one, UI hidden; svh is the small one, UI shown; dvh is whatever is visible right now. Plain vh is equivalent to lvh, which is why a 100vh hero is cut off on load on phones. I use svh for heroes and anything that must fit on load, dvh for app-like full-height layouts where tracking the visible area matters, accepting that it relayouts during scroll, and vh or lvh for backgrounds. The on-screen keyboard doesn't change these units by default; interactive-widget=resizes-content opts in on Chrome for Android.

Open in topic →

Invalid at computed-value time

CSS
:root { --size: 20px; }
.parent { color: green; }
.child  { color: blue; color: var(--size); }
HTML
<div class="parent"><p class="child">What colour am I?</p></div>

What colour is the paragraph's text?

Show answer

Green, not blue. var(--size) produces 20px, which isn't a colour, and by then it's too late to go back to color: blue.

The declaration that wins, then fails
CSS
:root { --size: 20px; }
.parent { color: green; }
.child { color: blue; color: var(--size); }
.boxed { width: 120px; width: var(--size-word); --size-word: wide; height: 10px; background: #fde68a; }
HTML
<div class="parent"><p class="child">What colour am I?</p></div>
<div class="boxed"></div>
Resultlive, in your browser
What’s happening
  1. At parse time the browser can't know what var(--size) will become, so it accepts color: var(--size) as valid. It's the later of the two color declarations, so the cascade picks it and throws color: blue away.
  2. At computed-value time the browser substitutes 20px, gets color: 20px, and finds it invalid. This is called invalid at computed-value time.
  3. The rule for that case: the property behaves as if it were set to unset. color is an inherited property, so unset means inherit, and the paragraph takes its parent's colour: measured rgb(0, 128, 0), green.
  4. For a property that doesn't inherit, unset means initial. The yellow .boxed bar shows it: width: var(--size-word) with --size-word: wide loses the earlier width: 120px and computes to auto, which here is the full 616px of the frame.
  5. The fix is to keep custom properties to one type, or to register the property with @property and a syntax (below), so an invalid value falls back to the registered initial value instead.
Open in topic →

Custom properties vs Sass variables

Show answer

"Sass variables are compile-time constants: they're substituted when the CSS is built and don't exist in the browser. CSS custom properties are real properties on elements: they cascade and inherit, so I can override one for a component or a theme, change it in a media query, or set it from JavaScript, and every var() that uses it updates live. var() is resolved at computed-value time, which is why a value of the wrong type makes the property fall back to unset instead of the previous declaration. If I need a typed property, for example to animate an angle in a gradient, I register it with @property."

Open in topic →

How would you implement dark mode?

Show answer

"I'd define semantic colour tokens as custom properties on :root and make every component use only those. Dark mode is a second set of values for the same tokens, applied by @media (prefers-color-scheme: dark) for the system default and by a data-theme attribute on <html> when the user picks one explicitly. I'd set color-scheme to match, so form controls, scrollbars and system colours go dark too, and I can use light-dark() for one-off values. To avoid a flash of the wrong theme, the saved choice is applied by a small inline script in the head before first paint."

Open in topic →

Native nesting vs Sass nesting

Show answer

"Native CSS nesting works in every current browser and has been Baseline since late 2023, widely available since mid-2026. It looks like Sass, but & is a real selector that behaves like :is() of the parent, so a parent list like .a, #b gives every nested rule the id's specificity, and you can't concatenate strings like &__element the way BEM in Sass does. Nested rules without & are treated as descendants, and you can nest media and container queries directly in a rule. I keep it to one or two levels so specificity stays flat."

Open in topic →

Why use logical properties?

Show answer

"Logical properties describe layout relative to the writing direction instead of the screen: inline is the direction text runs, block is the direction lines stack, each with a start and an end. If I write margin-inline-start and border-inline-start instead of left, the component mirrors correctly in a right-to-left language with no extra rules, and inline-size and block-size even follow vertical writing modes. They've been widely supported for years, so in new code I default to them, keeping in mind that shorthands like margin and inset with four values are still physical."

Open in topic →

clamp() in a narrow container

.title { width: clamp(200px, 50%, 300px); } What width does .title get inside a 300 px wide container, and inside an 800 px one?

Show answer

200 px in the 300 px container and 300 px in the 800 px one.

CSS
.title { width: clamp(200px, 50%, 300px); height: 16px; background: #a7f3d0; }
HTML
<div style="width: 300px"><div class="title"></div></div>
<div style="width: 800px"><div class="title"></div></div>
Resultlive, in your browser
What’s happening
  1. In the 300 px container the preferred value 50% is 150px. That's below the minimum, so clamp() returns the minimum, 200px. Measured: 200.
  2. In the 800 px container 50% is 400px. That's above the maximum, so it returns 300px. Measured: 300.
  3. Only a container between 400 and 600 px wide would use the preferred value itself. A common slip is to read the middle argument as "the value" and forget that the bounds win whenever it's outside them.
  4. If the minimum is larger than the maximum, the minimum wins: clamp(MIN, VAL, MAX) is defined as max(MIN, min(VAL, MAX)).
Open in topic →

When would you use clamp() instead of media queries?

Show answer

"clamp(min, preferred, max) gives me a value that scales continuously with its container or the viewport but never goes outside the bounds, so for things like fluid font sizes, gaps and widths I don't need a staircase of breakpoints. It's evaluated at layout time, so it can mix units, like clamp(1rem, 2.5vw + 0.5rem, 2rem). I still use media or container queries when the layout itself changes, for example moving from one column to two, because math functions only change a value, not the structure."

Open in topic →

Why would you use oklch() over hex or hsl()?

Show answer

"OKLCH is perceptually uniform: its lightness channel matches how bright a colour actually looks, which HSL's doesn't, so I can generate a consistent palette by changing lightness or hue and keep contrast predictable. It can also express wide-gamut P3 colours. With color-mix() I can derive tints, shades and transparent versions from one token, like color-mix(in oklch, var(--brand), white 40%), and relative colour syntax lets me do maths on the channels. Both have been Baseline since 2023, and for old browsers a hex declaration before the OKLCH one is enough of a fallback."

Open in topic →

text-wrap: balance vs pretty

Show answer

"text-wrap: balance makes the browser choose breaks so all lines are about the same length, which fixes headings that end with one short word. It's limited to a few lines because it's expensive, so I use it on headings and captions. text-wrap: pretty keeps normal ragged wrapping but looks ahead to avoid orphans and bad breaks at the end of paragraphs, so it's for body text. Balance is Baseline since 2024; pretty isn't in Firefox yet, but both degrade to normal wrapping, so there's no reason not to use them."

Open in topic →

How do you use new CSS features safely?

Show answer

"Progressive enhancement: the baseline experience uses widely supported CSS, and new features are layered on top. For single values I rely on the cascade, writing the fallback declaration first, because a browser drops declarations it can't parse. When a whole block has to switch, I wrap it in @supports, which can test a property-value pair, a selector with selector(), and combine conditions with and, or and not. I remember that it only tests parsing, not whether the feature works in every context, and I check Baseline status on MDN to decide whether a fallback is needed at all."

Open in topic →

What's changed in CSS recently that you've used?

Show answer

"The biggest shifts are :has(), which finally gives us a parent or relational selector, and container queries, which let components respond to their own space instead of the viewport; both have been Baseline since 2023. Native nesting and cascade layers replaced a lot of what we used Sass and naming conventions for, and @scope is now Baseline too. For colour, oklch() and color-mix() let me derive a whole palette from one token. For motion, same-document view transitions became Baseline in late 2025 and @starting-style handles entry animations. Anchor positioning is close but not fully Baseline, so I'd still keep a fallback there."

Open in topic →

Transitions vs keyframe animations

Show answer

"A transition animates between two computed values when a property changes, so it needs a trigger, a state change like a class or :hover, and it only knows a start and an end. A keyframe animation runs as soon as animation-name applies, with as many intermediate keyframes as I like, and can loop, alternate, delay and fill. I use transitions for interactive state changes and animations for things that run on their own, like spinners or attention effects. Both show up in element.getAnimations(), so I can pause, seek or inspect them from JavaScript."

Open in topic →

Why does the animation snap back?

CSS
@keyframes slide-in { from { translate: -100% 0; } to { translate: 0 0; } }
.panel { translate: -100% 0; animation: slide-in 300ms ease-out; }

The panel slides in and then jumps back off-screen. Why, and what are two fixes?

Show answer

After 300 ms the animation ends and stops applying; the element's own style, translate: -100% 0, takes over again.

CSS
@keyframes slide-in { from { translate: -100% 0; } to { translate: 0 0; } }
.panel { width: 120px; height: 20px; background: #bbf7d0; translate: -100% 0; animation: slide-in 300ms ease-out; }
.panel.forwards { animation-fill-mode: forwards; }
.panel.fixed { translate: 0 0; }
HTML
<div class="panel" id="p1"></div>
<div class="panel forwards" id="p2"></div>
<div class="panel fixed" id="p3"></div>
Resultlive, in your browser
What’s happening
  1. While the animation runs, its keyframes override the element's translate. When it finishes, with no fill mode, it no longer applies: the first panel reads translate: -100% again, off to the left.
  2. Fix one: animation-fill-mode: forwards keeps the last keyframe after the end: the second panel stays at 0% (the animated value, interpolated from -100%). Simple, but the animation keeps overriding the property forever, so a later translate change in CSS won't show.
  3. Fix two (usually better): make the element's own style the end state (translate: 0 0) and let the animation only describe the journey from -100%. The third panel ends at 0px with nothing left applying.
Open in topic →

How do CSS animations work?

Show answer

"@keyframes defines named values at percentages of a timeline; the animation shorthand attaches it with a duration, easing, delay, iteration count, direction and fill mode. It starts as soon as the name applies. Fill mode controls what's shown outside the active period, which is the usual reason an animation snaps back at the end. Animated values override normal declarations, even inline styles, but not !important ones. From JavaScript, getAnimations() gives me CSSAnimation objects I can pause, seek or finish, and element.animate() uses the same model without CSS."

Open in topic →

What does transform change and what doesn't it?

Show answer

"A transform changes how an element is drawn, not where it is in layout. Neighbours don't move, offsetLeft doesn't change, only getBoundingClientRect shows the new position, which is why transforms and opacity are the cheap properties to animate: the browser can skip layout and often paint. Transform functions apply right to left around the transform-origin, so order matters. A transform also creates a stacking context and a containing block for fixed-position children, which is a common cause of a 'fixed' element scrolling with its parent."

Open in topic →

Explain the rendering pipeline

Show answer

"After a change, the browser recalculates styles, then does layout to compute every box's geometry, then paints the boxes into pixels, then composites the layers into a frame, ideally within 16 ms at 60 Hz. Different changes start at different points: geometry changes like width or margin need layout and everything after it, colour changes only need repaint, and transform or opacity on a composited layer only need compositing, which also runs off the main thread. That's why I animate transform and opacity, and why I avoid reading layout values right after writing styles, which forces layout to run synchronously."

Open in topic →

How many layouts?

JavaScript
const boxes = document.querySelectorAll(".box"); // 100 boxes
for (const box of boxes) {
  box.style.width = box.offsetWidth + 10 + "px";
}

How many times does the browser run layout during this loop, and how would you fix it?

Show answer

Up to 100 forced layouts, one per iteration after the first, plus the normal one at the next frame. Fix it by reading all widths first, then writing.

What’s happening
  1. Iteration 1 reads box.offsetWidth. If nothing was dirty, that's free; then it writes style.width, which dirties layout.
  2. Iteration 2 reads offsetWidth of the next box. Layout is dirty, so the browser must run it now to give a correct answer, then the write dirties it again. The same happens in every following iteration: a forced layout per box.
  3. Fix: const widths = [...boxes].map((b) => b.offsetWidth); first (one layout at most), then boxes.forEach((b, i) => (b.style.width = widths[i] + 10 + "px")); (writes only). The browser lays out once, at the next frame.
  4. The demo above proves the mechanism (each read after a write returned the fresh value, so layout ran each time). The exact count Chrome performs isn't exposed to the page; DevTools shows each one as a separate Layout event.
Open in topic →

What is layout thrashing and how do you avoid it?

Show answer

"The browser normally batches style changes and does layout once per frame. If JavaScript reads a geometry value like offsetHeight or getBoundingClientRect() after changing styles, the browser has to run layout synchronously to answer, which is a forced reflow. Doing that in a loop of write-read pairs is layout thrashing: N layouts instead of one. I avoid it by batching reads before writes, deferring writes to requestAnimationFrame, using ResizeObserver instead of polling sizes, and animating transform and opacity instead of geometry. For long pages, content-visibility: auto lets the browser skip rendering off-screen sections entirely."

Open in topic →

Why are transform and opacity cheap to animate?

Show answer

"Because they don't affect layout or other elements' painting. The browser can paint the element once into its own compositor layer and then, every frame, only change how that layer is positioned, scaled or blended, which the compositor thread does on the GPU, even while the main thread is busy. Animating width, margin or left means layout and paint on the main thread every frame. will-change: transform lets the browser create the layer ahead of time, but layers cost memory and will-change creates a stacking context and containing block, so I use it sparingly. For layout changes I use FLIP or view transitions so the motion itself is a transform."

Open in topic →

How do you handle reduced motion?

Show answer

"I treat motion as an enhancement: the component works without it, and large or continuous movement is added inside @media (prefers-reduced-motion: no-preference), so anyone who set 'reduce motion' in their OS doesn't get it. Reduced doesn't mean none: I swap slides and zooms for fades rather than removing feedback. JavaScript animations check matchMedia('(prefers-reduced-motion: reduce)') and listen for changes. Many resets also add a global rule that shortens all animations and transitions to almost zero under reduce, which I keep as a backstop, and I test with the DevTools emulation."

Open in topic →

How do you animate an element appearing and disappearing in CSS?

Show answer

"For the entrance I use @starting-style to give the element the values it should transition from on its first style, like opacity: 0 and a small translate, because otherwise a newly inserted or newly displayed element has no previous value and doesn't transition. For the exit, display: none would hide it instantly, so I add display to the transition with allow-discrete, which keeps it displayed until the transition ends; for dialogs and popovers I also transition overlay so they stay in the top layer. @starting-style and transition-behavior are Baseline 2024, but Firefox doesn't transition display yet, so there the exit is instant, which is an acceptable fallback."

Open in topic →

What are view transitions?

Show answer

"The View Transition API animates between two DOM states for me. I wrap the DOM update in document.startViewTransition(); the browser snapshots the old state, runs my update, snapshots the new one, and animates between them with pseudo-elements: a cross-fade by default, and for elements with a view-transition-name, a morph of their position and size, like a native FLIP. I can customise it with CSS on ::view-transition-group(), -old() and -new(). Same-document transitions became Baseline in October 2025; cross-document ones, enabled with @view-transition { navigation: auto }, are in Chrome and Safari. I always keep a fallback that just runs the update, and turn the animation off for reduced motion."

Open in topic →

How do you stop CSS from slowing down the first paint?

Show answer

"Stylesheets in the head are render-blocking, so I keep the critical path short: inline the CSS the first screen needs, load the rest with ordinary links rather than @import chains so they download in parallel, give print or other non-matching stylesheets a media attribute so they don't block, and keep blocking scripts out of the head with defer. For fonts I preload the one or two the first screen needs, with crossorigin, set font-display: swap or optional, and size-adjust the fallback so the swap doesn't shift layout. Then I check it with Lighthouse and the Performance panel rather than guessing."

Open in topic →

Swap the file order

Using the demo's four rules, suppose the bundler now loads blog.css before checkout.css. What colour is each heading?

Show answer

"Order summary" turns blue, the two sidebar headings don't change (green and purple).

What’s happening
  1. The two .title rules still have equal specificity (0,1,0), so source order decides. Now checkout.css comes last, so its color: rgb(29, 78, 216) wins for every .title that nothing stronger targets.
  2. "Related posts" is still matched by #sidebar .title (1,1,0), which beats any single class regardless of order: green.
  3. "Sale" still has an !important declaration. Important declarations beat all normal ones whatever their specificity or order: purple.
  4. So only the element whose winner was decided by order changed. That's why order-dependent CSS is fragile: the same files produce different pages when they are concatenated differently.
Open in topic →

Why does CSS become hard to maintain at scale?

Show answer

Because every selector is global and every rule competes in one cascade, so nothing ties a style to the component it was written for. Two files that both use .title style each other's elements, and when specificity is equal the winner is whichever loaded last, which in a code-split app can change between builds. Teams fix conflicts by adding specificity (ids, longer chains, !important), which makes the next override harder, and they never delete old CSS because they can't tell what still uses it. Every architecture approach targets these forces: naming conventions like BEM and generated names like CSS Modules solve the global namespace, utilities avoid writing new selectors, and cascade layers and @scope give the cascade a structure that doesn't depend on file order.

Open in topic →

What's wrong with these class names?

HTML
<div class="card">
  <div class="card__header">
    <h3 class="card__header__title title--big">Pro</h3>
  </div>
</div>
Show answer

Two problems: card__header__title encodes the DOM path, and title--big is a modifier without its block.

What’s happening
  1. In BEM, elements are flat children of the block, whatever their depth in the markup. The title should be card__title. With card__header__title, moving the title out of the header (a common redesign) means renaming the class everywhere it's used.
  2. title--big modifies a block called title, but there is no title class on the element, so no base styles apply and the modifier has nothing to modify. It should be a modifier of the element: card__title card__title--big.
  3. Also check title--big against the legacy .title rule from the previous topic: a team that half-adopts BEM still has generic names in play, and the collisions come back.
Open in topic →

What is BEM and what problem does it solve?

Show answer

BEM is a naming convention: Block, Element, Modifier, written block__element--modifier, for example card, card__title and card--featured. It solves two problems without any tooling. First, the global namespace: because every class carries its block name, .card__title can't collide with another component's .title. Second, specificity: every rule is a single class, so specificity stays flat at (0,1,0) and you never need ids or !important to override. Variants are extra classes on the same element (card card--featured), elements are named after the block not the DOM path, and platform states like :disabled or aria-expanded are used instead of state classes where they exist. The cost is long class names and discipline, which is why many teams now get the same guarantees from CSS Modules or utilities instead.

Open in topic →

How do CSS Modules work?

Show answer

A CSS Module is a normal CSS file that the build tool treats as locally scoped: every class name is rewritten to a unique generated name, such as .title becoming ._title_4ut92_6, and importing the file gives JavaScript an object mapping your names to the generated ones. So two components can both use .title with no collision, because neither class is actually called title in the browser. It's plain CSS at runtime with no JavaScript cost; composes reuses another class by adding its name to the class list, and :global() opts a selector out of renaming. The limits are that only class names are scoped, dynamic values still need custom properties or inline styles, and generated names must never be hard-coded.

Open in topic →

Does the dark theme work?

Using scope.scss above, what colour is a .link inside <div class="dark">, and why?

Show answer

#2563eb, the light-theme blue. The dark value never makes it into the CSS.

What’s happening
  1. Sass evaluates .dark .link { color: $brand; } at compile time, looking $brand up lexically. The only $brand in scope at that point is the global #2563eb; the $brand assigned inside .dark { } was local to that block and is gone.
  2. So the compiled rule is .dark .link { color: #2563eb; }, a constant. The browser has no idea a variable was ever involved.
  3. Fix it with a custom property (vars.scss), or by writing the value directly in the .dark .link rule. If you really wanted to change the global, Sass has !global, but that changes it for every rule after that point in the file, still not per element.
Open in topic →

Preprocessors vs modern CSS

Show answer

A preprocessor like Sass compiles a superset of CSS into plain CSS at build time, adding variables, nesting, mixins, functions, loops and a module system with @use. The crucial difference from native features is timing: Sass variables are resolved during the build and become constants, while custom properties are resolved by the browser per element at runtime, so only custom properties can drive theming, dark mode or values set from JavaScript. Native CSS now covers nesting, colour mixing and math, so many new projects skip Sass; it still earns its place for mixins, loops over maps and organising large token sets. If you use it, use Dart Sass with @use and module functions, because @import and global functions have been deprecated since 1.80 and are slated for removal in Dart Sass 3.

Open in topic →

Utility-first CSS: pros and cons

Show answer

Utility-first means composing small single-purpose classes like px-4 or bg-blue-600 in the markup instead of writing a semantic class and its CSS for every component. Tailwind scans the source for class names and generates only the utilities actually used, so the CSS stays small, there are no naming decisions, every selector has the same low specificity, and deleting markup deletes its CSS. Its constraints come from a theme, so spacing and colours stay consistent. The costs are long class lists, a vocabulary to learn, class names that must appear whole in the source, and the need for components in your framework to avoid repeating the same twenty classes. In Tailwind 4 the configuration is in CSS with @theme, and the output uses cascade layers, so unlayered legacy CSS will beat utilities unless you layer it.

Open in topic →

Runtime vs zero-runtime CSS-in-JS

Show answer

CSS-in-JS lets you write component styles in JavaScript with generated, collision-free class names and styles that can depend on props. Runtime libraries like styled-components and Emotion evaluate, hash and inject the CSS in the browser during render, so they cost JavaScript size and render time, duplicate whole rule blocks for every distinct prop value, need extra work for server rendering, and don't work in React Server Components without making the component a client component. Zero-runtime libraries like vanilla-extract, Panda or StyleX run the style code at build time and ship a static CSS file plus class-name strings, keeping the authoring benefits with the runtime profile of plain CSS, at the cost of a build plugin and values that must be known at build time. For dynamic values, both families end up using CSS custom properties.

Open in topic →

What do PostCSS and Autoprefixer do?

Show answer

PostCSS is a tool that parses CSS into a syntax tree, runs plugins over it and prints CSS again; on its own it changes nothing. Autoprefixer is the best-known plugin: it uses caniuse data and your Browserslist targets to add vendor-prefixed copies like -webkit-user-select only where one of your target browsers needs them, prefixed first and standard last. postcss-preset-env goes further and lowers modern syntax, for example flattening nesting or converting oklch() to rgb() for old targets. The output is purely a function of the target list, so the Browserslist config, shared with Babel, is the real decision. Today Lightning CSS, used by Tailwind 4 and optionally by Vite, does parsing, prefixing, lowering and minifying in one fast Rust step.

Open in topic →

Reset vs normalize

Show answer

Browsers apply a user-agent stylesheet with default margins, heading sizes, list padding and form-control fonts. A hard reset like Eric Meyer's removes nearly all of it so every element starts identical; normalize.css instead keeps useful defaults and only fixes cross-browser inconsistencies, and it hasn't needed a release since 2018 because browsers converged. Modern projects use a small modern reset: box-sizing: border-box everywhere, zero margins, block-level images with max-width: 100%, and font: inherit on form controls, which is roughly what Tailwind's Preflight does. I'd put it in the lowest cascade layer or behind :where() so it never wins a specificity fight, and never remove focus outlines without replacing them.

Open in topic →

How would you choose a styling approach for a new project?

Show answer

I'd start from constraints: team experience, whether we render on the server or use React Server Components, whether there's a design system, and how long the code will live. For a component-based app I'd pick either CSS Modules or Tailwind: both have no runtime cost and both solve the global namespace, Modules by generating class names and Tailwind by not writing selectors at all. I'd keep design tokens as CSS custom properties so theming works at runtime, declare a cascade layer order such as reset, base, vendor, components, utilities so third-party CSS and overrides are predictable, and avoid runtime CSS-in-JS for new work because of its rendering cost, its friction with Server Components and styled-components being in maintenance mode. Whatever the choice, the goals are flat specificity, no reliance on file order, and styles that can be deleted with the component they belong to.

Open in topic →

Which level?

A client says "we need to be WCAG compliant". Which level do you aim for, and which version?

Show answer

WCAG 2.2 Level AA. Level AA is what laws and procurement rules reference; AAA is not expected for whole sites.

What’s happening
  1. Conformance levels are cumulative: AA means every A and every AA criterion (55 in WCAG 2.2) is met. There is no "AA except for the hard ones".
  2. The EU (via EN 301 549 v3.2.1) and the US ADA Title II rule cite WCAG 2.1 AA; WCAG 2.2 AA includes all of 2.1 AA except the removed 4.1.1 Parsing, so meeting 2.2 AA satisfies both and anticipates EN 301 549 v4.1.1.
  3. Conformance is per page (and per complete process, like a checkout), so one inaccessible step breaks the whole flow.
  4. AAA criteria are still worth adopting where they're cheap, such as 2.5.5's 44px targets or 1.4.6's 7:1 contrast for body text.
Open in topic →

What is web accessibility, and what is WCAG?

Show answer

Accessibility means people with disabilities, including screen-reader users, keyboard-only users, people with low vision, colour blindness, hearing loss, motor or cognitive impairments, can use what we build. Technically, the browser exposes an accessibility tree with a role, name, state and value for each element, and assistive technology reads that tree, so semantic HTML and correct names matter more than visuals. WCAG 2.2 is the W3C standard (also ISO/IEC 40500:2025), organised under four principles, Perceivable, Operable, Understandable and Robust, with 86 testable success criteria at levels A, AA and AAA. Level AA is the legal and contractual target: the European Accessibility Act, in force since June 2025, points to EN 301 549, which maps to WCAG 2.1 AA, and the US ADA Title II rule requires WCAG 2.1 AA. I'd target WCAG 2.2 AA because it covers both and adds criteria like focus not obscured and 24px target sizes.

Open in topic →

What's the first rule of ARIA?

Show answer

If a native HTML element or attribute already has the semantics and behaviour you need, use it instead of adding ARIA to something else. ARIA only changes what an element reports to assistive technology; it never adds behaviour. So <div role="button"> announces as a button but isn't focusable without tabindex="0", doesn't respond to Enter or Space, can't be disabled and doesn't submit forms, unless you write all of that in JavaScript. A real <button> does all of it for free and works in high-contrast modes. ARIA is for things HTML can't express, like aria-expanded on a disclosure button, aria-live regions or composite widgets such as tabs, and even there "no ARIA is better than bad ARIA".

Open in topic →

Roles, states and properties

Show answer

A role says what an element is, such as button, tab, dialog or navigation, and most HTML elements already have an implicit one, so explicit roles are mainly for custom widgets. Properties like aria-label, aria-labelledby, aria-describedby and aria-controls describe names and relationships, while states like aria-expanded, aria-pressed, aria-checked, aria-selected and aria-current describe the current condition and must be updated by script as the user interacts. I treat the ARIA state as the single source of truth: the script flips the attribute and the CSS styles off [aria-expanded="true"], so what's announced and what's shown can't drift apart. And an explicit role overrides native semantics, so role="button" on a heading removes the heading.

Open in topic →

How is an element's accessible name computed?

Show answer

The browser follows the accessible name computation: it uses aria-labelledby first, joining the text of the referenced elements, then aria-label, then the native mechanism, like a <label> for inputs or alt for images, then the element's own text content for roles like buttons and links, and finally title or placeholder as a fallback. The first source that produces text wins and the rest are ignored, so an aria-label silently overrides a visible label, which can break the Label in Name criterion for voice-control users. Visually hidden text counts towards the name and aria-hidden content doesn't, which is how icon buttons get names. Descriptions via aria-describedby are separate, secondary text such as hints or errors.

Open in topic →

How do you make a custom widget keyboard accessible?

Show answer

First I'd check whether a native element does it, because buttons, links, form controls, <details> and <dialog> come with focus and key handling. Otherwise every interactive element needs to be focusable, which means tabindex="0" in DOM order or -1 for script-only focus, never a positive value, plus a visible focus style and key handlers that match the ARIA Authoring Practices pattern: Enter and Space for buttons, arrow keys inside composites like toolbars and tabs using a roving tabindex so the whole widget is a single Tab stop. For modals I'd use <dialog> with showModal(), which moves focus in, makes the rest of the page inert, closes on Escape and returns focus to the opener. And I'd keep the DOM order matching the visual order, since Tab follows the DOM, not CSS.

Open in topic →

:focus vs :focus-visible

Show answer

:focus matches any focused element, including a button the user just clicked with the mouse, while :focus-visible matches only when the browser decides a focus indicator is useful: after keyboard navigation, always for text inputs, and generally not after a mouse click on a button. So I style rings with :focus-visible, which keeps keyboard users' indicator and stops designers asking to remove it, and I never write outline: none without a replacement, because that fails WCAG 2.4.7. A good ring has 3:1 contrast against its surroundings, an offset so it's distinct from the border, and uses outline rather than only box-shadow, because forced colors mode removes shadows. WCAG 2.2 also requires the focused element not to be completely hidden by sticky headers, which scroll-padding-top fixes.

Open in topic →

Does this button pass?

A button has white text (#fff) on #3b82f6 at 15px, normal weight. It also has a 1px #3b82f6 border on a white page. Which criteria apply and does it pass?

Show answer

The text fails 1.4.3 (3.68:1, below 4.5:1 for normal text). The border is fine, because the button's background itself is the boundary (3.68:1 against white, above 3:1 for 1.4.11).

What’s happening
  1. Text at 15px normal weight isn't large (large starts at 24px, or about 18.66px bold), so the requirement is 4.5:1.
  2. Running the formula: #3b82f6 has a relative luminance of about 0.235, white is 1.0, so (1.0 + 0.05) / (0.235 + 0.05) ≈ 3.68. Fail.
  3. For 1.4.11, the visual boundary of the button (its blue fill against the white page) needs 3:1: 3.68 passes. The border adds nothing because it's the same colour.
  4. Fixes: darken to #2563eb (5.17:1, measured in the demo), or make the text bold at 18.66px or larger, where 3:1 is enough.
Open in topic →

How do you handle colour contrast?

Show answer

WCAG 2.2 AA requires a contrast ratio of 4.5:1 for normal text and 3:1 for large text, which is 24px or about 18.66px bold, and 3:1 for UI component boundaries, focus indicators and meaningful graphics. The ratio comes from relative luminance, (lighter + 0.05) divided by (darker + 0.05), so #767676 is the lightest grey that passes on white at 4.54:1. Separately, colour must never be the only signal: errors need text or an icon as well as red, and links in body text need an underline or another non-colour cue unless they have 3:1 against the surrounding text. I check contrast in DevTools and with axe in CI, and re-check every pair in dark mode, since it's a separate set of colours.

Open in topic →

Visually hidden vs aria-hidden vs display none

Show answer

They hide from different audiences. display: none, the hidden attribute and visibility: hidden hide content from everyone: it's not rendered, not in the accessibility tree and not focusable. A visually hidden class, using absolute positioning, a 1px box and clip-path: inset(50%), hides content from the eye but keeps it in the accessibility tree, so screen readers read it; that's how icon buttons get names and links get context like "Read more about pricing". aria-hidden="true" does the opposite: content stays visible but is removed from the tree, for decorative icons or duplicates, and it must never be put on something focusable. opacity: 0 hides nothing from assistive tech or the keyboard.

Open in topic →

How do you make form errors accessible?

Show answer

Every field gets a visible label linked with for and id, related radios and checkboxes are grouped with fieldset and legend, and hints and errors are linked to the field with aria-describedby so they're read when it gets focus. On submit I validate, set aria-invalid="true" on each failing field, write a specific error in text with a suggestion like "Enter an email like name@example.com", and move focus to the first invalid field or to an error summary whose links jump to each field. Errors are never conveyed by colour alone, the submit button stays enabled, and autocomplete attributes let browsers fill personal data. I don't rely on aria-errormessage alone yet, because screen-reader support is still incomplete.

Open in topic →

How do you announce dynamic changes to screen-reader users?

Show answer

I use a live region: an element with role="status" (polite) for confirmations and result counts, or role="alert" (assertive) only for urgent errors, which screen readers announce whenever its content changes without moving focus, as WCAG 4.1.3 requires. The region must already exist in the DOM, usually empty, before the message is written into it, and I clear it before writing so a repeated message still counts as a change. <output> is a native status region for calculated values. For errors after a form submit I usually move focus instead, to the field or an error summary, and I avoid having both, which causes double announcements. The newer ariaNotify() method announces without a DOM node, but it only arrived in the latest browser versions in 2025–2026, so I feature-detect it and keep the live region as the fallback.

Open in topic →

Lighthouse says 100

A page scores 100 in Lighthouse's accessibility audit. What can you claim?

Show answer

Only that none of the automated checks Lighthouse runs failed. You can't claim WCAG conformance.

What’s happening
  1. Lighthouse's accessibility score is computed from axe-core rules (a subset), weighted. A score of 100 means every rule it ran passed or didn't apply.
  2. The demo above shows what such rules miss: a div used as the primary button, colour-only required markers, vague link text, and a placeholder used as a label all pass automated checks.
  3. Many WCAG criteria are judgement calls (are alt texts accurate, are headings descriptive, is focus order meaningful, are errors helpful) or need interaction (keyboard traps, focus not obscured).
  4. So: automated checks are necessary, cheap, and catch the most common failures; conformance needs manual keyboard and screen-reader testing on top.
Open in topic →

How do you test accessibility?

Show answer

In layers. Automated tools like axe-core, through Lighthouse, a browser extension or @axe-core/playwright in CI, catch machine-checkable failures such as missing names and alt text, contrast and invalid ARIA, but they find only a fraction of issues; on a test page of mine axe found three out of seven problems and missed a div used as the pay button. Component tests query by role and accessible name with Testing Library's getByRole, so they fail when semantics break. Then manual testing: keyboard-only passes through every flow checking focus visibility, order and traps; screen-reader testing with VoiceOver and NVDA, using headings, landmarks and forms; and zoom to 400% for reflow. A Lighthouse score of 100 means the automated rules passed, not that the page conforms to WCAG.

Open in topic →

Predict: which of these can a keyboard user reach?

HTML
<div class="btn">Save</div>
<button>Save</button>
<a>Docs</a>
<a href="/docs">Docs</a>

Each one has a click handler attached in JavaScript. What does each one expose to a screen reader, and which ones can you Tab to?

Show answer

Only the <button> and the <a href>. The div and the <a> without href both come out as role generic with no name and can't be focused, so a keyboard user can't reach them and a screen reader doesn't announce them as controls. The <button> is a focusable button named "Save" that also activates with Enter and Space; the <a href> is a focusable link named "Docs" that activates with Enter. The rule I'd state: a button does something on this page, a link goes somewhere, and an <a> with no href is neither.

Roles and focus, measured
CSS
.btn { display: inline-block; padding: 4px 12px; border-radius: 6px; background: #2563eb; color: #fff; }
HTML
<div class="btn">Save</div>
<button>Save</button>
<a>Docs</a>
<a href="/docs">Docs</a>
Resultlive, in your browser
What’s happening
  1. The div styled as a button looks identical to a real one, but its role is generic and its name is empty: assistive tech sees an anonymous box. focus() on it does nothing, so Tab skips it and Enter or Space can never trigger the click handler.
  2. The <button> is a button named "Save" (from its text), it's in the tab order, and the browser turns Enter and Space into a click for you. That's the free behaviour you'd otherwise rebuild with tabindex="0", role="button" and a keydown handler.
  3. <a>Docs</a> without href is a placeholder link: role generic, not focusable. Its tabIndex property still reads 0, which is a trap if you check focusability that way; the test only got focus onto elements that are really focusable.
  4. <a href="/docs"> is a link named "Docs" and focusable. A link also gets "open in new tab", copy and bookmark, which is why navigation should be a link and not a button with location.href.
  5. If you changed the div to <div role="button" tabindex="0">, the role and focus would be fixed, but Enter and Space still wouldn't click it: ARIA changes what's announced, never what happens.

Learn more: Semantic HTML and why it matters, Links and navigation and The first rule of ARIA.

Open in topic →

Predict: what does this form put in the URL?

HTML
<form action="/search" method="get">
  <input name="q" value="css grid">
  <input value="unnamed">
  <input name="lang" value="en" disabled>
  <input type="checkbox" name="exact" checked>
  <input type="checkbox" name="safe">
  <select name="sort">
    <option>newest</option>
    <option value="top" selected>Top rated</option>
  </select>
  <button name="go" value="1">Search</button>
</form>

The user clicks Search without changing anything. What's the query string?

Show answer

?q=css+grid&exact=on&sort=top&go=1. The form data set contains every control that has a name, isn't disabled and, for checkboxes and radios, is checked, plus the button that submitted the form if it has a name. Values are URL-encoded, so the space becomes +, a checkbox without a value sends on, and a select sends its selected option's value.

The form data set, built by the browser
HTML
<form action="/search" method="get">
  <input name="q" value="css grid">
  <input value="unnamed">
  <input name="lang" value="en" disabled>
  <input type="checkbox" name="exact" checked>
  <input type="checkbox" name="safe">
  <select name="sort">
    <option>newest</option>
    <option value="top" selected>Top rated</option>
  </select>
  <button name="go" value="1">Search</button>
</form>
Resultlive, in your browser
What’s happening
  1. q has a name and a value, so it's sent as q=css+grid: the application/x-www-form-urlencoded format encodes a space as +.
  2. The second input has no name, so it's left out completely; lang is disabled, so it's left out too (a readonly field would have been sent).
  3. exact is checked and has no value attribute, so it sends the default on. safe is unchecked, so the key doesn't appear at all, which is why servers treat a missing checkbox as "false".
  4. The select sends the selected option's value, top, not its text "Top rated". The first option has no value, so when it's selected it sends its text, newest, which the test confirmed.
  5. The button's name=value pair is only included when that button submitted the form. new FormData(form, button) builds the same list the browser sends on that click, and the test confirmed the click submits with the button as event.submitter.

Learn more: How a form submits and select, datalist and textarea.

Open in topic →

Predict: which fields are labelled?

HTML
<label for="email">Email</label> <input id="email" type="email">
<label>Phone <input id="phone" type="tel"></label>
<label>City</label> <input id="city">
<input id="search" placeholder="Search">

What accessible name does each input get, and which labels can you click to focus the field?

Show answer

Email and Phone are labelled; City and Search aren't. for/id and wrapping are the two ways to associate a <label>, and both give the input its name and make the label text clickable. A <label> next to an input without for is just text, so City has no name at all. Search does get a name, "Search", because Chrome falls back to the placeholder as a last resort, but a placeholder isn't a label: it disappears as soon as you type and is usually too faint to read.

Names and label clicks
CSS
label, input { margin: 4px 8px 4px 0; }
HTML
<label for="email">Email</label> <input id="email" type="email"><br>
<label>Phone <input id="phone" type="tel"></label><br>
<label>City</label> <input id="city"><br>
<input id="search" placeholder="Search">
Resultlive, in your browser
What’s happening
  1. <label for="email"> points at the input's id, so email.labels has one entry, the name is "Email", and clicking the label text moves focus into the field.
  2. The wrapping label needs no ids: the input inside it is its labelled control, so Phone gets the same two benefits.
  3. The City label has no for and doesn't wrap anything, so the browser can't connect it: labels.length is 0, the name is empty and clicking "City" does nothing. Visually it looks labelled, which is why this bug survives code review.
  4. Search has no label at all. Its name "Search" comes from the placeholder, the last step of the name computation, but the hint vanishes when the user types and placeholder text usually fails contrast, so it's still a failure.

Learn more: Labels and accessible names for inputs and Accessible names and descriptions.

Open in topic →

Predict: :invalid vs :user-invalid on page load

CSS
input:invalid      { outline: 3px solid crimson; }
input:user-invalid { background: #fee2e2; }
HTML
<form>
  <input id="email" type="email" required>
  <input id="site" type="url" value="example.com">
  <button>Send</button>
</form>

Which fields have the red outline and which have the pink background when the page loads? And after the user presses Send?

Show answer

On load both fields have the red outline and neither is pink. After Send, both are pink, the submit is cancelled and focus goes to the email field. :invalid matches whenever the value fails a constraint, including before the user has typed anything, which is why forms styled with it shout at people on arrival. :user-invalid waits until the user has changed the field and moved on, or has tried to submit, and that's the one to style errors with.

Before and after a submit attempt
CSS
input { margin-right: 6px; }
input:invalid      { outline: 3px solid crimson; }
input:user-invalid { background: #fee2e2; }
HTML
<form>
  <input id="email" type="email" required>
  <input id="site" type="url" value="example.com">
  <button>Send</button>
</form>
Resultlive, in your browser
What’s happening
  1. The email field is required and empty (valueMissing), and the URL field holds example.com, which has no scheme, so it fails type="url" (typeMismatch). Both match :invalid from the first frame and get the crimson outline.
  2. Neither matches :user-invalid yet, because the user hasn't interacted with either, so neither background is pink. A value written in the markup doesn't count as interaction.
  3. Pressing Send runs interactive validation (the test calls requestSubmit(), which does the same). The browser finds invalid fields, cancels the submit (no submit event fired), focuses the first invalid one and shows its message.
  4. A submit attempt also flips every field's "user validity" flag, so both now match :user-invalid and turn pink at once. That's the behaviour you want: quiet until the user acts, then every problem flagged together.

Learn more: Styling valid and invalid fields and Built-in validation.

Open in topic →

Predict: is the hidden banner hidden?

CSS
.banner { display: flex; gap: 8px; padding: 8px; background: #fef3c7; }
HTML
<div class="banner" hidden>Settings saved</div>
Show answer

No, it's visible. The hidden attribute works through one rule in the browser's own stylesheet, [hidden] { display: none }, and author CSS beats the user-agent origin whatever the specificity. So any display you set on the element, here flex, overrides it. The fix most resets include is [hidden] { display: none !important; }, which keeps the attribute in charge.

The attribute loses to display: flex
CSS
.banner { display: flex; gap: 8px; padding: 8px; margin-bottom: 8px; background: #fef3c7; }
.with-reset [hidden] { display: none !important; }
HTML
<div class="banner" id="plain" hidden>Settings saved</div>
<div class="with-reset"><div class="banner" id="reset" hidden>Settings saved</div></div>
Resultlive, in your browser
What’s happening
  1. hidden is an HTML attribute, but it has no magic of its own: Chrome's user-agent stylesheet maps it to display: none, a normal declaration in the lowest origin.
  2. The cascade compares origin before specificity, so the author rule .banner { display: flex } wins even though [hidden] would tie with a class. The test reads display: flex and a banner more than 20px tall: it shows.
  3. In the second box, the reset [hidden] { display: none !important; } (scoped to a wrapper here so both cases fit in one demo) beats the normal display: flex, so the box is gone: display: none, height 0.
  4. That's why !important is acceptable here: the attribute's whole job is to hide, so nothing should be able to override it by accident.

Learn more: Global attributes and !important.

Open in topic →

Predict: which button does Enter press?

HTML
<form>
  <input name="q">
  <button>Clear</button>
  <button type="submit">Search</button>
</form>

The Clear button has a click handler that empties the field. The user types and presses Enter. What happens?

Show answer

The browser presses Clear. A <button> without a type is a submit button, and pressing Enter in a text field triggers the form's default button, the first submit button in tree order, by firing a click on it. So the field is emptied by Clear's handler and the form is submitted with Clear as the submitter. The fix is type="button" on every button that isn't meant to submit.

The form's default button
HTML
<form>
  <input name="q">
  <button id="clear">Clear</button>
  <button type="submit" id="search">Search</button>
</form>
Resultlive, in your browser
What’s happening
  1. $("#clear").type is "submit": the missing attribute defaults to submit inside a form. So the form has two submit buttons, and the first in tree order is its default button.
  2. The :default pseudo-class matches exactly that button, and the test found it on Clear. Implicit submission (Enter in a single-line field) fires a click on the default button; the test can't press a real Enter key, so it relies on :default for which button that is.
  3. Clicking Clear submitted the form with event.submitter set to Clear. So with Enter, Clear's handler empties the field and then the form submits, the opposite of what the user wanted.
  4. After setting Clear's type to button, :default moves to Search, and Enter now submits with Search. That's why type="button" belongs on every toggle, "add row" or "clear" button in a form.

Learn more: Buttons in forms.

Open in topic →

Predict: how many landmarks does this page have?

HTML
<header>Site name</header>
<main>
  <article>
    <header><h2>Post title</h2></header>
    <p>…</p>
    <footer>Posted 20 Oct</footer>
  </article>
  <section><h2>Comments</h2></section>
  <section aria-labelledby="rel"><h2 id="rel">Related</h2></section>
</main>
<footer>© 2026</footer>

A screen-reader user opens the landmarks list. What's in it?

Show answer

Four: banner, main, the region "Related", and contentinfo. Only the page-level header and footer become the banner and contentinfo landmarks; inside an article they're section header and footer parts, not landmarks. A section is only a region landmark when it has an accessible name, so the unnamed Comments section is a plain generic box. The article itself is exposed as an article, which isn't a landmark either.

Roles of each sectioning element
HTML
<header id="h-page">Site name</header>
<main id="m">
  <article id="art">
    <header id="h-art"><h2>Post title</h2></header>
    <p>Text of the post.</p>
    <footer id="f-art">Posted 20 Oct</footer>
  </article>
  <section id="s-comments"><h2>Comments</h2></section>
  <section id="s-related" aria-labelledby="rel"><h2 id="rel">Related</h2></section>
</main>
<footer id="f-page">© 2026</footer>
Resultlive, in your browser
What’s happening
  1. The top-level <header> and <footer> come out as banner and contentinfo: the landmarks that let a user jump to the site header or footer.
  2. The same elements inside the article come out as sectionheader and sectionfooter in Chrome 155. That context rule keeps a page with twenty cards from having twenty banners.
  3. <main> is the main landmark, and there should be one per page. The article has role article, useful for "next article" navigation but not in the landmarks list.
  4. The Comments section has no accessible name, so it's generic; the Related one is named by its heading through aria-labelledby, which makes it a region called "Related". The test counted exactly four landmark roles.

Learn more: Landmarks and sectioning.

Open in topic →

Explain: defer vs async

HTML
<head>
  <script src="analytics.js" async></script>
  <script src="vendor.js" defer></script>
  <script src="app.js" defer></script>
</head>

When does each script run, and why is this the right attribute for each?

Show answer

Both attributes download the script in parallel with parsing; they differ in when it runs. defer scripts run after the whole document is parsed, in document order, just before DOMContentLoaded, so vendor.js always runs before app.js and both can use the full DOM. An async script runs as soon as it arrives, interrupting the parser if it's still going, in no guaranteed order, which suits independent code like analytics. A plain <script src> without either blocks parsing while it downloads and runs, and module scripts behave like defer by default.

What’s happening
  1. The parser meets all three tags at the top of the page and starts all three downloads at once, without stopping: that's what both attributes buy over a plain script.
  2. analytics.js runs the moment its download finishes. That might be before or after the body is parsed, and before or after the other two, so it must not depend on the DOM being complete or on vendor.js.
  3. vendor.js and app.js wait until parsing is done, then run in the order they appear, even if app.js finished downloading first. So app.js can rely on what vendor.js defines and on every element in the page.
  4. DOMContentLoaded fires after the deferred scripts have run; async scripts don't hold it up. Neither attribute has any effect on an inline <script> without src (a module inline script is the exception: it's deferred).
  5. If you changed app.js to async, it could run before vendor.js and fail on an undefined global, intermittently, depending on network timing.

Learn more: The document skeleton and How a browser turns HTML into a page.

Open in topic →

Predict: how wide are these two boxes?

CSS
.a, .b { width: 200px; padding: 20px; border: 5px solid #64748b; margin: 10px; }
.b     { box-sizing: border-box; }

Two siblings in a flex row: .a then .b. How wide is each box on screen, how wide is each content area, and how far apart are they?

Show answer

.a is 250px wide with a 200px content area; .b is 200px wide with a 150px content area; they're 20px apart. With the default content-box, width sizes only the content, so padding and border are added on top: 200 + 2 × 20 + 2 × 5. With border-box, width is the border box, so padding and border come out of the content: 200 − 50 = 150. Margins are outside both, and horizontal margins never collapse, so 10 + 10 = 20px.

The two boxes measured
CSS
.row   { display: flex; }
.a, .b { width: 200px; padding: 20px; border: 5px solid #64748b; margin: 10px; background: #e0f2fe; }
.b     { box-sizing: border-box; background: #fef3c7; }
HTML
<div class="row"><div class="a">a</div><div class="b">b</div></div>
Resultlive, in your browser
What’s happening
  1. .a uses content-box: content 200, plus 20 + 20 padding and 5 + 5 border, so the test measured a 250px-wide box. Its clientWidth (content plus padding) is 240, so the content is 200.
  2. .b uses border-box: the border box is exactly 200, so the content shrinks to 200 − 40 − 10 = 150.
  3. Both have margin: 10px. .a's right margin and .b's left margin sit side by side, 20px in total; only vertical margins in block layout collapse, and these are horizontal flex items anyway.
  4. Both report width: 200px in computed style, so reading width doesn't tell you the rendered size. That's why resets set box-sizing: border-box everywhere: width: 100% plus padding then still fits its parent.

Learn more: The box model and box-sizing.

Open in topic →

Predict: where does the child's margin go?

CSS
.intro  { height: 20px; }
.parent { background: #bfdbfe; }
.child  { margin-top: 30px; height: 50px; }
HTML
<div class="intro"></div>
<div class="parent"><div class="child"></div></div>

How tall is .parent, and where is the 30px gap?

Show answer

.parent is 50px tall, and the 30px gap appears above it, outside its blue background. The child's top margin touches the parent's top margin (there's no padding, border or content between them), so the two collapse into one margin that belongs to the parent. Fix it with display: flow-root on the parent (or any padding or border), which stops the collapse: the parent becomes 80px tall and the gap is inside it.

The margin escapes, then the fix
CSS
.case   { display: flow-root; width: 200px; margin-bottom: 12px; outline: 1px dashed #94a3b8; }
.intro  { height: 20px; background: #fde68a; }
.parent { background: #bfdbfe; }
.child  { margin-top: 30px; height: 50px; background: #60a5fa; }
.fixed .parent { display: flow-root; }
HTML
<div class="case" id="bug"><div class="intro"></div><div class="parent"><div class="child"></div></div></div>
<div class="case fixed" id="fix"><div class="intro"></div><div class="parent"><div class="child"></div></div></div>
Resultlive, in your browser
What’s happening
  1. .parent has no padding, border or inline content above .child, so the child's 30px top margin is adjoining the parent's own top margin (0). Adjoining vertical margins collapse into one: max(0, 30) = 30px.
  2. The collapsed margin sits on the outside of the parent, so the parent moves down 30px from .intro and the child starts exactly at the parent's top edge: the gap is white, not blue, and the parent is only 50px tall.
  3. display: flow-root makes the parent a new block formatting context, and margins never collapse through a formatting-context root. Now the 30px stays inside: the parent is 80px tall and the child sits 30px below its top.
  4. Each .case wrapper is itself flow-root, so the escaping margin can't escape any further and the two cases measure independently. On a real page the margin would keep escaping until something stopped it, sometimes pushing the whole page down from <body>.

Learn more: Margin collapsing.

Open in topic →

Predict: which colour wins?

CSS
:is(#main, .card) .title { color: crimson; }
.card h2.title.big       { color: green; }
:where(#main, .card) .title.big.x { color: navy; }
HTML
<div class="card"><h2 class="title big x">Hello</h2></div>

There's no #main anywhere on the page.

Show answer

Crimson. :is() takes the specificity of its most specific argument, whether or not that argument matched, so the first rule counts as (1, 1, 0): an id beats any number of classes. The second rule is (0, 3, 1). :where() always adds zero, so the third is only (0, 3, 0). Remove the first rule and green wins.

The specificity, proved by removing a rule
CSS
:is(#main, .card) .title { color: crimson; }
.card h2.title.big       { color: green; }
:where(#main, .card) .title.big.x { color: navy; }
HTML
<div class="card"><h2 class="title big x">Hello</h2></div>
Resultlive, in your browser
What’s happening
  1. The page has no #main, so :is(#main, .card) matches through .card. Specificity is worked out from the selector, not from what matched: :is() takes its strongest argument, #main, so the rule scores (1, 1, 0).
  2. .card h2.title.big has three classes and one type: (0, 3, 1). Comparing column by column from the left, the id column decides: 1 beats 0, so crimson wins even though green looks more specific.
  3. :where(#main, .card) contributes nothing, so the third rule is just its three classes, (0, 3, 0), and loses to the second on the type column.
  4. The test deleted the :is() rule from the stylesheet and the heading turned green, which proves the second rule was runner-up. That's why libraries wrap their defaults in :where(): easy to override, and why :is() with an id inside quietly makes a rule hard to beat.

Learn more: Specificity and :is(), :where(), :not() and :has().

Open in topic →

Predict: layers, ids and !important

CSS
@layer base, theme;
@layer theme { #note { color: green; } }
p { color: navy; }

@layer base  { .msg { color: crimson !important; } }
@layer theme { .msg { color: purple !important; } }
.loud { color: orange !important; }
HTML
<p id="note">A</p>
<p class="msg">B</p>
<p class="msg loud">C</p>

What colour is each paragraph?

Show answer

A is navy, B is crimson, C is crimson. Layers are compared before specificity. For normal declarations, unlayered styles beat every layer, so a bare p beats #note in a layer. For !important the order flips: the earliest layer wins, and important declarations in any layer beat unlayered important ones. So base's crimson beats theme's purple and the unlayered orange.

Three paragraphs, three cascade decisions
CSS
@layer base, theme;
@layer theme { #note { color: green; } }
p { color: navy; }

@layer base  { .msg { color: crimson !important; } }
@layer theme { .msg { color: purple !important; } }
.loud { color: orange !important; }
HTML
<p id="note">A</p>
<p class="msg">B</p>
<p class="msg loud">C</p>
Resultlive, in your browser
What’s happening
  1. A has two normal declarations: #note in the theme layer, (1, 0, 0), and p unlayered, (0, 0, 1). The cascade checks layers before specificity, and unlayered normal styles count as the last, strongest layer, so navy wins and the id never gets compared.
  2. B has two important declarations, in base and theme. Importance reverses the layer order, so the first-declared layer, base, is the strongest: crimson. The reversal is deliberate: a reset layer can mark something !important and later layers can't take it away.
  3. C adds an unlayered .loud { color: orange !important }, with higher specificity than .msg. It still loses: among important declarations unlayered ones are the weakest, so crimson again.
  4. The pattern to remember: for normal rules the order is base < theme < unlayered; for !important it's unlayered < theme < base. That's why third-party CSS imported into an early layer can't be beaten by your unlayered !important.

Learn more: Cascade layers with @layer, The cascade and !important.

Open in topic →

Predict: what does the link inherit?

CSS
.notice { color: #166534; font-weight: bold; border: 2px solid; padding: 8px; }
HTML
<p class="notice">Read the <a href="#terms">terms</a>, then <button>Accept</button></p>

What colour and weight are the link text and the button text, and what colour is the border?

Show answer

The link is the browser's link blue (rgb(0, 0, 238)) but bold; the button is black, normal weight and a smaller size; the border is green. Inheritance only fills in a property that no rule sets at all, and the browser's own stylesheet sets color on links and color and font on buttons, so those don't inherit. Nothing sets font-weight on a link, so it inherits bold. The border has no colour, so it uses currentColor, the element's own green. That's why resets add a { color: inherit } and button { font: inherit; color: inherit }.

Inherited and not inherited
CSS
.notice { color: #166534; font-weight: bold; border: 2px solid; padding: 8px; }
HTML
<p class="notice">Read the <a href="#terms">terms</a>, then <button>Accept</button></p>
Resultlive, in your browser
What’s happening
  1. color is an inherited property, but the user-agent stylesheet has a rule for :link that sets it to rgb(0, 0, 238). Any matching declaration beats inheritance (an inherited value has no specificity at all), so the link stays blue.
  2. The browser doesn't set font-weight on links, so the property is unset on the <a> and it inherits the paragraph's 700: the link is bold.
  3. Buttons get color: buttontext and a whole font shorthand from the browser, so they ignore the paragraph's colour, weight and size: black, 400 and 13.3333px in Chrome.
  4. border isn't inherited, so the link has none. The paragraph's border: 2px solid names no colour, so it uses the initial currentColor, which resolves to the paragraph's own green.

Learn more: Inheritance and the keywords and Resets and normalize.

Open in topic →

Predict: which hidden child can come back?

HTML
<div style="visibility: hidden"><span style="visibility: visible">A</span></div>
<div style="display: none"><span style="display: block">B</span></div>
<div style="opacity: 0"><span style="opacity: 1">C</span></div>

Which letters can you see, and which can you click?

Show answer

You see only A. A and C can be clicked; B doesn't exist on screen at all. visibility is inherited, so a child can set visibility: visible and reappear inside a hidden parent, which still keeps its space. display: none removes the whole subtree from layout, and nothing a child sets can bring it back. opacity applies to the element and everything inside it as one group, so a child's opacity: 1 can't undo the parent's 0, but the invisible C still takes clicks and focus.

Three ways to hide, with children opting back in
CSS
.row { display: flex; gap: 10px; }
.box { width: 120px; height: 40px; background: #bfdbfe; }
.box span { display: block; width: 40px; height: 40px; background: #fbbf24; text-align: center; line-height: 40px; }
HTML
<div class="row">
  <div class="box" id="v" style="visibility: hidden"><span id="a" style="visibility: visible">A</span></div>
  <div class="box" id="d" style="display: none"><span id="b" style="display: block">B</span></div>
  <div class="box" id="o" style="opacity: 0"><span id="c" style="opacity: 1">C</span></div>
</div>
Resultlive, in your browser
What’s happening
  1. The first box is visibility: hidden: it keeps its 120px of space but isn't painted or hit-tested; the test's point inside it, beside A, didn't land on it. Its child sets visibility: visible, which wins over the inherited hidden, so A is painted and clickable.
  2. The second box is display: none, so neither it nor B has a box: both measure 0 wide, and the third box sits 10px (the gap) after the first, as if the second weren't there. B's display: block changes nothing because its parent generates no box for it to live in.
  3. The third box has opacity: 0. Opacity is applied to the rendered group, element plus descendants, so C's own opacity: 1 is multiplied by the parent's 0: it's invisible (check the live result above: there's no C). The test can't read pixels, so that part is the spec's rule and what you can see in the frame.
  4. But C is still hit-tested: elementFromPoint at its position returned C. An opacity: 0 element is still clickable, focusable and announced, which is why it's a trap as a final "hidden" state.

Learn more: Hiding things and Hiding content.

Open in topic →

Predict: em vs rem

CSS
.page  { font-size: 20px; }
.card  { font-size: 1.25em; padding: 1em; }
.title { font-size: 1.5em; padding-left: 1em; margin-bottom: 1rem; }
HTML
<div class="page"><div class="card"><h2 class="title">Title</h2></div></div>

The root font size is the browser default, 16px. Work out the card's font size and padding, and the title's font size, left padding and bottom margin.

Show answer

Card: 25px font, 25px padding. Title: 37.5px font, 37.5px left padding, 16px bottom margin. In font-size, em is relative to the parent's font size; in any other property, it's relative to the element's own computed font size, so em compounds as you nest. rem is always the root's font size, so 1rem is 16px wherever it's used. I default to rem for type and spacing and use em where something should scale with its component, like a button's padding.

Computed sizes
CSS
.page  { font-size: 20px; }
.card  { font-size: 1.25em; padding: 1em; background: #f1f5f9; }
.title { font-size: 1.5em; padding-left: 1em; margin: 0 0 1rem; }
HTML
<div class="page"><div class="card"><h2 class="title">Title</h2></div></div>
Resultlive, in your browser
What’s happening
  1. .card { font-size: 1.25em } multiplies the parent's size: 1.25 × 20 = 25px. Its padding: 1em is then relative to its own font size, 25px.
  2. .title { font-size: 1.5em } multiplies the card's 25px: 37.5px. Its padding-left: 1em uses its own 37.5px. Three levels of em have already turned "1em" into three different lengths.
  3. margin-bottom: 1rem ignores all of that and uses the root's 16px. The 20px on .page doesn't change rem, because rem looks only at <html>.
  4. If you changed .page to 30px, every em value would grow and the rem margin would stay 16px. That compounding is useful inside a component and painful across a page, which is why rem is the default for type.

Learn more: CSS units.

Open in topic →

Predict: percentage padding and height

CSS
.parent { width: 300px; }
.child  { height: 50%; padding-top: 50%; }

The parent has no height set and .child has no content. How tall is .child on screen?

Show answer

150px, all of it padding. Percentage padding, vertical included, is resolved against the containing block's width, so 50% of 300px is 150px. A percentage height needs a definite height on the parent, and this parent's height is auto, so height: 50% behaves as auto, which is 0 for an empty box. This is the old padding-top aspect-ratio trick, which aspect-ratio has replaced.

The child measured
CSS
.parent { width: 300px; background: #e2e8f0; }
.child  { height: 50%; padding-top: 50%; background: #93c5fd; }
HTML
<div class="parent"><div class="child"></div></div>
Resultlive, in your browser
What’s happening
  1. padding-top: 50% resolves against the containing block's width, 300px, giving 150px. All four paddings and margins use the width, so a box's padding can't depend on its own height.
  2. height: 50% would need the parent's height, but the parent's height is auto, worked out from its children, which would be circular. So the percentage is treated as auto, and an empty block's auto height is 0px.
  3. The rendered box is padding plus content, 150 + 0 = 150px, with the 300px width giving a 2:1 shape. Before aspect-ratio, this was how you sized a responsive video box.
  4. Give the parent height: 200px and the child's height: 50% would become 100px, with the 150px padding added on top (in content-box).

Learn more: Width, height and intrinsic sizing and aspect-ratio and object-fit.

Open in topic →

Explain: centre a box both ways

"Centre this card inside its container, horizontally and vertically. Give me more than one way."

Show answer

Grid with place-items: center, flexbox with justify-content and align-items (or margin: auto on the child), or absolute positioning with inset: 0; margin: auto for a known size or translate(-50%, -50%) for an unknown one. Grid and flex are the default answers; the absolute versions are for overlays that shouldn't affect layout. For only horizontal centring of a block, margin-inline: auto with a width is enough.

Three centring techniques, measured
CSS
.box   { width: 200px; height: 120px; margin-bottom: 10px; background: #f1f5f9; }
.card  { width: 60px; height: 40px; background: #93c5fd; }
.grid  { display: grid; place-items: center; }
.flex  { display: flex; }
.flex .card { margin: auto; }
.abs   { position: relative; }
.abs .card { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
HTML
<div class="box grid"><div class="card"></div></div>
<div class="box flex"><div class="card"></div></div>
<div class="box abs"><div class="card"></div></div>
Resultlive, in your browser
What’s happening
  1. Grid: place-items: center is align-items plus justify-items, so the single item sits in the middle of its one grid area: 70px from the sides (200 − 60 = 140, halved) and 40px from the top and bottom (120 − 40 = 80, halved).
  2. Flex: margin: auto on a flex item absorbs the free space on both axes equally, giving the same offsets. Unlike justify-content: center, auto margins stay "safe": if the card were bigger than the box, it would overflow at the end instead of being cut off at the start.
  3. Absolute: top: 50%; left: 50% puts the card's top-left corner at the centre of the positioned parent, and translate(-50%, -50%) moves it back by half its own size, so it works without knowing that size.
  4. All three gave identical offsets of 70px and 40px in the test. In an interview, mention the condition each needs: a grid or flex parent, or a positioned ancestor for the absolute version.

Learn more: Centering things: every way.

Open in topic →

Predict: flex: 1 vs flex: auto

CSS
.row { display: flex; width: 400px; }
.one  > div { flex: 1; }
.auto > div { flex: auto; }

Each row has two items. The first item's content is 100px wide, the second's is 20px. How wide is each item in each row?

Show answer

With flex: 1 both are 200px; with flex: auto they're 240px and 160px. flex: 1 is 1 1 0%: a zero basis, so all 400px is free space and it's split equally regardless of content. flex: auto is 1 1 auto: each item starts at its content size, 100 and 20, and only the remaining 280px is split, 140 each.

Both rows measured
CSS
.row { display: flex; width: 400px; margin-bottom: 8px; outline: 1px dashed #94a3b8; }
.row > div { height: 30px; background: #e0f2fe; outline: 1px solid #7dd3fc; }
.row i { display: block; height: 30px; background: #fbbf24; }
.one  > div { flex: 1; }
.auto > div { flex: auto; }
HTML
<div class="row one"><div><i style="width: 100px"></i></div><div><i style="width: 20px"></i></div></div>
<div class="row auto"><div><i style="width: 100px"></i></div><div><i style="width: 20px"></i></div></div>
Resultlive, in your browser
What’s happening
  1. flex: 1 expands to flex-grow: 1; flex-shrink: 1; flex-basis: 0%, which the test read from computed style. Both items start at 0, the free space is the full 400px, and equal grow factors split it 200/200.
  2. The content doesn't matter here because both items' minimum (their content, 100 and 20) is below 200. If one item's content were wider than its share, min-width: auto would stop it shrinking further (next question).
  3. flex: auto is 1 1 auto: the basis is the item's content size, 100 and 20. The free space is 400 − 120 = 280px, split 140 each.
  4. So the items end at 100 + 140 = 240 and 20 + 140 = 160. Use flex: 1 for equal columns and flex: auto when bigger content should get more room.

Learn more: The flex shorthand and flex-grow, flex-shrink and flex-basis.

Open in topic →

Predict: why does the layout overflow?

CSS
.layout { display: flex; width: 300px; }
.side   { flex: none; width: 100px; }
.main   { flex: 1; }
.wide   { width: 400px; }   /* say, a code block or a table inside .main */

How wide is .main, and what do you change so it stays inside the 300px layout?

Show answer

.main is 400px, so the layout sticks out by 200px. Flex items default to min-width: auto, which means they won't shrink below their content's minimum width, here the 400px child, even with flex: 1. Setting min-width: 0 on .main removes that floor: it shrinks to the 200px it was given, and the wide content overflows inside it, where overflow-x: auto makes it scroll.

The overflow and the fix
CSS
.layout { display: flex; width: 300px; margin-bottom: 12px; outline: 2px dashed #94a3b8; }
.side   { flex: none; width: 100px; height: 30px; background: #fde68a; }
.main   { flex: 1; background: #e0f2fe; }
.wide   { width: 400px; height: 30px; background: linear-gradient(90deg, #93c5fd, #c4b5fd); }
.fixed .main { min-width: 0; overflow-x: auto; }
HTML
<div class="layout" id="bug"><div class="side"></div><div class="main"><div class="wide"></div></div></div>
<div class="layout fixed" id="fix"><div class="side"></div><div class="main"><div class="wide"></div></div></div>
Resultlive, in your browser
What’s happening
  1. The free space is 300 − 100 = 200px, and flex: 1 asks for .main to be 200px. But its automatic minimum is its min-content width, which is the 400px .wide box, and a flex item never shrinks below its minimum.
  2. So .main is 400px and its right edge is 200px past the layout's; on a phone that's the page wider than the screen and a sideways scroll.
  3. min-width: 0 replaces the automatic minimum with zero, so .main gets exactly its 200px share and lines up with the layout's edge.
  4. The wide content now overflows .main itself, and overflow-x: auto turns that into a scroll area: scrollWidth is 400 inside a 200px box. Any overflow other than visible also removes the automatic minimum on its own; the same problem in a column is min-height: auto.

Learn more: Why flex items overflow.

Open in topic →

Predict: auto-fill vs auto-fit with two items

CSS
.fill { display: grid; width: 500px; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }
.fit  { display: grid; width: 500px; grid-template-columns: repeat(auto-fit,  minmax(100px, 1fr)); }

Each grid has only two items. How wide is each item?

Show answer

100px in the auto-fill grid and 250px in the auto-fit grid. Both create as many 100px-minimum columns as fit, five in 500px. auto-fill keeps the three empty columns, so they still take their share of the space and the items stay 100px. auto-fit collapses the empty columns to zero, so the two items' 1fr tracks share the whole row.

Two items, five possible columns
CSS
.g { display: grid; width: 500px; margin-bottom: 8px; outline: 1px dashed #94a3b8; }
.g div { height: 30px; background: #c7d2fe; outline: 1px solid #818cf8; }
.fill { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }
.fit  { grid-template-columns: repeat(auto-fit,  minmax(100px, 1fr)); }
HTML
<div class="g fill"><div></div><div></div></div>
<div class="g fit"><div></div><div></div></div>
Resultlive, in your browser
What’s happening
  1. Both grids first count how many tracks fit using the minimum: floor(500 / 100) = 5. So both have five columns before anything else happens.
  2. auto-fill leaves all five in place. The 1fr maximum shares the leftover space between five tracks, but there's none left, so each is 100px and the two items sit in the first two, with three empty columns after them.
  3. auto-fit then collapses every track that has no item to 0px, which the test read from grid-template-columns: 250px 250px 0px 0px 0px. The two real tracks split the 500px.
  4. With five or more items the two behave identically. Pick auto-fill when cards should keep a consistent size, auto-fit when a few items should spread out.

Learn more: repeat(), minmax() and auto-fill vs auto-fit.

Open in topic →

Predict: z-index 9999 that loses

CSS
.header { position: absolute; top: 0;    width: 240px; height: 50px; z-index: 2; }
.page   { position: absolute; top: 30px; width: 240px; height: 90px; z-index: 1; }
.modal  { position: absolute; top: -20px; left: 40px; width: 120px; height: 60px; z-index: 9999; }
HTML
<div class="header"></div>
<div class="page"><div class="modal"></div></div>

The modal is inside .page and overlaps the header. Which one is on top where they overlap?

Show answer

The header. .page is positioned with z-index: 1, so it creates a stacking context, and everything inside it is painted as one unit at level 1. The modal's 9999 only orders it within .page; against the header, it's .page's 1 against the header's 2. The fix is to change the ancestor: remove .page's z-index (or move the modal out, or use <dialog>, which goes to the top layer).

The trap, and the ancestor fixed
CSS
.stage  { position: relative; isolation: isolate; height: 130px; margin-bottom: 10px; }
.header { position: absolute; top: 0; left: 0; width: 240px; height: 50px; z-index: 2; background: #fde68a; }
.page   { position: absolute; top: 30px; left: 0; width: 240px; height: 90px; z-index: 1; background: #e2e8f0; }
.modal  { position: absolute; top: -20px; left: 40px; width: 120px; height: 60px; z-index: 9999; background: #f9a8d4; }
.fixed .page { z-index: auto; }
HTML
<div class="stage" id="bug"><div class="header"></div><div class="page"><div class="modal"></div></div></div>
<div class="stage fixed" id="fix"><div class="header"></div><div class="page"><div class="modal"></div></div></div>
Resultlive, in your browser
What’s happening
  1. The modal's top edge is 20px above .page's, so its upper part overlaps the header (y 10 to 50 in the stage). The test picks a point in that overlap and asks the browser which element is hit there.
  2. In the first stage, the stage's stacking context holds two children: the header at z-index: 2 and .page at z-index: 1, which forms its own context because it's positioned with a z-index. The header wins, and the modal inside .page goes down with it.
  3. The 9999 is real, but it's only compared with .page's other descendants. No number inside a context can lift a child above something that beats the context itself.
  4. In the second stage .page has z-index: auto, so it no longer forms a context. The modal now competes directly in the stage's context, 9999 against 2, and wins. Remember that opacity, transform and filter create contexts too, without any z-index.

Learn more: z-index and stacking contexts.

Open in topic →

Predict: where does the fixed toast go?

CSS
.card  { transform: translateX(0); margin: 40px 0 0 60px; width: 200px; height: 80px; }
.toast { position: fixed; top: 0; left: 0; }
HTML
<div class="card"><div class="toast">Saved</div></div>

Is the toast at the top-left of the viewport?

Show answer

No, it's at the top-left of the card. A transform on an ancestor (even one that does nothing, like translateX(0)) makes that ancestor the containing block for fixed-position descendants, so top: 0; left: 0 is measured from the card and the toast scrolls with it. filter, perspective, contain: layout and will-change: transform do the same. Put toasts and modals outside transformed ancestors, or in the top layer with popover or <dialog>.

Fixed inside a transformed card
CSS
.card  { margin: 40px 0 0 60px; width: 200px; height: 80px; background: #e0e7ff; }
.moved { transform: translateX(0); }
.toast { position: fixed; top: 0; left: 0; width: 80px; height: 24px; background: #fca5a5; }
HTML
<div class="card moved" id="moved"><div class="toast">Saved</div></div>
<div class="card" id="plain"><div class="toast">Saved</div></div>
Resultlive, in your browser
What’s happening
  1. Normally a fixed element's containing block is the viewport, which is what the second card's toast shows: it's at (0, 0), even though its parent is further down the page.
  2. The first card has transform: translateX(0). Visually that changes nothing, but any transform other than none makes the element a containing block for absolute and fixed descendants.
  3. So the first toast's top: 0; left: 0 resolves against the card's padding box, and the test found it exactly at the card's top-left corner, (72, 40) in the frame (the 12px body margin plus the card's 60px; the card's 40px top margin collapses with the body's 12px), not at the viewport's.
  4. In real code the transform usually comes from an animation library or a will-change someone added for performance, far from the toast's own CSS. When a fixed element scrolls or is clipped, look up its ancestors for one of these properties.

Learn more: position: fixed and Transforms.

Open in topic →

Predict: why doesn't the header stick?

CSS
.scroller { height: 150px; overflow: auto; }
.sticky   { position: sticky; top: 0; height: 30px; }
HTML
<div class="scroller">
  <div class="wrap"><h3 class="sticky">Inbox</h3></div>
  <div class="content"><!-- 400px of messages --></div>
</div>

The user scrolls the list down by 100px. Where's the header?

Show answer

It scrolls away with the list. A sticky element can only stick while it stays inside its containing block, here .wrap, and .wrap is exactly as tall as the header, so there's no room to move: as soon as .wrap scrolls off, the header goes with it. Make the header a direct child of the element that contains the content (or make the wrapper contain the content too), and it sticks.

Scrolled by 100px
CSS
.scroller { height: 150px; width: 220px; overflow: auto; margin-bottom: 12px; outline: 1px solid #94a3b8; }
.sticky   { position: sticky; top: 0; height: 30px; margin: 0; background: #fde68a; }
.content  { height: 400px; background: linear-gradient(#e0f2fe, #bfdbfe); }
HTML
<div class="scroller" id="bug"><div class="wrap"><h3 class="sticky">Inbox</h3></div><div class="content"></div></div>
<div class="scroller" id="fix"><h3 class="sticky">Inbox</h3><div class="content"></div></div>
Resultlive, in your browser
What’s happening
  1. Both headers have position: sticky; top: 0 and both scrollers are the nearest scroll container, so the threshold is the same: "don't go above the scroller's top edge".
  2. In the first scroller, the header's containing block is .wrap, 30px tall. Sticky offsets are limited to the containing block, and a 30px header in a 30px box has 0px to travel, so after scrolling 100px it's 100px above the scroller's top, out of view.
  3. In the second scroller, the header's containing block is the scroller's content (430px tall), so it has room: it stays at offset 0 while the messages scroll under it.
  4. The other two classic causes: an ancestor between the header and the intended scroller with overflow: hidden or auto (that becomes the scroll container instead), and a missing top. Use overflow: clip if you need clipping without breaking sticky.

Learn more: position: sticky.

Open in topic →

Predict: justify-content in a column

CSS
.col  { display: flex; flex-direction: column; justify-content: center; width: 200px; height: 200px; }
.item { width: 60px; height: 40px; }

Where does the single item end up?

Show answer

Centred vertically, at the left. justify-content always works on the main axis, and in a column the main axis is vertical, so it centres the item top to bottom. The horizontal position is the cross axis, controlled by align-items, whose default stretch can't stretch an item with a fixed width, so it sits at the start. Add align-items: center to centre it both ways.

The item in a column
CSS
.col  { display: flex; flex-direction: column; justify-content: center; width: 200px; height: 200px; background: #f1f5f9; }
.item { width: 60px; height: 40px; background: #93c5fd; }
HTML
<div class="col"><div class="item"></div></div>
Resultlive, in your browser
What’s happening
  1. flex-direction: column makes the main axis run top to bottom, so justify-content: center splits the free vertical space, 200 − 40 = 160, equally: 80px above the item.
  2. The cross axis is now horizontal. align-items defaults to normal, which behaves as stretch in flexbox, but stretch only applies to items with an auto cross size, and this item is 60px wide.
  3. So the item sits at the cross-start edge, the left: 0px from the container's left side.
  4. The quick rule: justify-* follows flex-direction, align-* is the other axis. In grid it's different: justify is always the inline axis and align the block axis.

Learn more: justify-content, align-items and align-content and The flex model.

Open in topic →

Explain: grid or flexbox?

"When would you use grid and when flexbox?"

Show answer

Flexbox is one-dimensional and content-out; grid is two-dimensional and layout-in. Flexbox lays items along one line and sizes them from their content, and when they wrap each line is independent, so it suits toolbars, nav bars, button groups and tags. Grid defines rows and columns first and places items into them, so things line up in both directions: page skeletons, galleries, forms with aligned labels, and sibling cards aligned with subgrid. Most pages use both, grid for the macro layout and flex inside components.

What’s happening
  1. Start from the question "do I need alignment in both directions?" If items in one row must line up with items in the next row, that's grid; flex rows don't know about each other.
  2. Then ask who drives the sizes. In flexbox the content does: a long label makes its item wider. In grid the tracks do, and content only influences them through auto, min-content or fr minimums.
  3. A wrapping flex row with a short last line stretches those last items wider; repeat(auto-fill, minmax(…)) in grid keeps them in the same columns. That's the usual "my card grid looks wrong" answer.
  4. Both share gap and the alignment properties, so switching costs little. Mention subgrid (aligning the insides of sibling cards) as the thing only grid can do.

Learn more: Grid or flexbox? and Common flexbox layouts.

Open in topic →

Predict: the base rule after the media query

CSS
@media (width >= 600px) {
  .nav { display: flex; }
}
.nav { display: block; }

.menu { display: block; }
@media (width >= 600px) {
  .menu { display: flex; }
}

What's the display of .nav and of .menu at 360px and at 800px?

Show answer

.nav is block at both widths; .menu is block at 360px and flex at 800px. A media query is only a condition; it adds nothing to specificity. At 800px both .nav rules apply with equal specificity, so the later one, display: block, wins. Mobile-first only works when the base styles come first and the min-width queries after them.

The two orders at two widths
CSS
@media (width >= 600px) {
  .nav { display: flex; }
}
.nav { display: block; }

.menu { display: block; }
@media (width >= 600px) {
  .menu { display: flex; }
}
.nav, .menu { gap: 8px; padding: 6px; margin-bottom: 8px; background: #f1f5f9; }
.nav span, .menu span { display: inline-block; padding: 2px 8px; background: #c7d2fe; }
HTML
<nav class="nav"><span>Home</span> <span>Docs</span></nav>
<nav class="menu"><span>Home</span> <span>Docs</span></nav>
Resultlive, in your browser
What’s happening
  1. At 360px the condition (width >= 600px) is false, so only the unconditional rules apply: both elements are block.
  2. At 800px both .nav rules match. They have the same specificity, (0, 1, 0), and being inside @media doesn't change that, so the cascade falls through to source order: the base rule comes later and wins. The test read block at both widths.
  3. .menu has the same rules in mobile-first order: base first, enhancement after. At 800px the later rule is the media query's, so flex wins.
  4. In a real codebase this happens when someone appends a "fix" at the end of a file. Keep each component's base rule above its queries, or nest the queries inside the rule so the order is obvious.

Learn more: Responsive design and mobile-first and Media queries.

Open in topic →

Predict: media query or container query?

CSS
.sidebar { width: 250px; container-type: inline-size; }
.main    { flex: 1; container-type: inline-size; }
.card    { display: grid; }
@media (width >= 600px)     { .card.mq { grid-template-columns: 80px 1fr; } }
@container (width >= 400px) { .card.cq { grid-template-columns: 80px 1fr; } }

On an 800px-wide screen, the sidebar holds one .mq card and one .cq card, and the main column (about 500px) holds a .cq card. Which cards go side by side (image next to text)?

Show answer

The .mq card in the sidebar and the .cq card in the main column; the .cq card in the sidebar stays stacked. A media query asks about the viewport, which is 800px everywhere on the page, so the .mq card switches to two columns even when it's squeezed into a 250px sidebar. A container query asks about the nearest container, so the same .cq component is stacked in the 250px sidebar and side by side in the wider main column.

One viewport, two containers
CSS
.layout  { display: flex; gap: 10px; }
.sidebar { width: 250px; container-type: inline-size; }
.main    { flex: 1; container-type: inline-size; }
.card    { display: grid; gap: 6px; margin-bottom: 10px; padding: 6px; background: #f1f5f9; }
.thumb   { height: 40px; background: #c7d2fe; }
.text    { height: 40px; background: #fde68a; }
@media (width >= 600px)     { .card.mq { grid-template-columns: 80px 1fr; } }
@container (width >= 400px) { .card.cq { grid-template-columns: 80px 1fr; } }
HTML
<div class="layout">
  <aside class="sidebar">
    <div class="card mq" id="side-mq"><div class="thumb"></div><div class="text"></div></div>
    <div class="card cq" id="side-cq"><div class="thumb"></div><div class="text"></div></div>
  </aside>
  <div class="main">
    <div class="card cq" id="main-cq"><div class="thumb"></div><div class="text"></div></div>
  </div>
</div>
Resultlive, in your browser
What’s happening
  1. The viewport is 800px, so (width >= 600px) is true for every element on the page. The .mq card gets its two columns in the sidebar too, leaving only about 150px for the text: the classic "the component looks crushed in the sidebar" bug.
  2. container-type: inline-size on .sidebar and .main makes each a size container. @container looks up from the card to its nearest container and tests that container's width.
  3. For the sidebar's .cq card that's 250px, below 400, so it stays one column: the text sits under the image. For the main column's card it's 516px (776px of body width minus 250 and the 10px gap), so it goes side by side.
  4. Same markup, same class, two layouts: that's the point of container queries. Media queries stay the right tool for page-level layout and user preferences like prefers-reduced-motion.

Learn more: Container queries and Media queries.

Open in topic →

Predict: clamp() at three widths

CSS
h1 { font-size: clamp(1rem, 0.5rem + 2.5vw, 2rem); }

What font size does the heading get on a 360px, an 800px and a 1400px viewport?

Show answer

17px, 28px and 32px. clamp(min, preferred, max) returns the preferred value limited to the range. The preferred value here is 8px plus 2.5% of the viewport width: 8 + 9 = 17px at 360px, 8 + 20 = 28px at 800px, and 8 + 35 = 43px at 1400px, which the 2rem (32px) maximum caps. Keeping a rem part means the size still follows the user's font-size setting.

The heading at each width
CSS
h1 { font-size: clamp(1rem, 0.5rem + 2.5vw, 2rem); margin: 0; }
HTML
<h1>Fluid heading</h1>
Resultlive, in your browser
What’s happening
  1. 0.5rem is 8px and 1vw is 1% of the viewport width, so the preferred value is 8 + 0.025 × width px.
  2. At 360px: 8 + 9 = 17px, inside the range 16 to 32, so 17px is used. The test read 17px.
  3. At 800px: 8 + 20 = 28px, still inside the range: 28px.
  4. At 1400px: 8 + 35 = 43px, above the 32px maximum, so clamp() returns 32px. Working backwards, the size is flat at 16px below 320px wide, grows linearly to 32px at 960px, and is flat above that.
  5. If the preferred value were plain 4vw, zooming the page wouldn't make the text bigger, which fails WCAG's resize-text requirement; the rem term and rem limits keep zoom working.

Learn more: Fluid typography with clamp() and Math functions.

Open in topic →

Predict: a custom property of the wrong type

CSS
:root  { --gap: 20px; --brand: #2563eb; }
.box   { color: navy; }
.box p { color: crimson; color: var(--gap); padding: 12px; padding: var(--brand); }
HTML
<div class="box"><p>Text</p></div>

What colour and padding does the paragraph get?

Show answer

Navy, and 0 padding: not crimson and 12px. A normal invalid declaration is dropped at parse time, so the earlier one would win. But the browser can't know what var() will contain until it computes the value, so color: var(--gap) is accepted, wins the cascade as the later declaration, and only then turns out to be invalid. At that point the property becomes unset: color is inherited, so it takes the parent's navy; padding isn't, so it takes its initial value, 0.

Invalid at computed-value time
CSS
:root  { --gap: 20px; --brand: #2563eb; }
.box   { color: navy; }
.box p { color: crimson; color: var(--gap); padding: 12px; padding: var(--brand); background: #f1f5f9; }
HTML
<div class="box"><p>Text</p></div>
Resultlive, in your browser
What’s happening
  1. At parse time, color: var(--gap) is valid syntax: any declaration containing var() is kept, because its value isn't known yet. So in the cascade it's simply the later of the two color declarations, and it wins.
  2. At computed-value time, the browser substitutes 20px into color and finds it's not a colour. The crimson declaration lost already and can't come back; instead the property behaves as unset.
  3. unset on an inherited property means inherit, so color becomes the parent's navy. The test read rgb(0, 0, 128).
  4. padding isn't inherited, so unset means initial, 0px. If you want a fallback for a possibly wrong value, use @property to register the variable's type with an initial value, or a fallback inside var(--x, fallback), which only helps when the variable is missing, not when it has the wrong type.

Learn more: Custom properties and Feature detection with @supports.

Open in topic →

Predict: which cards does :has() match?

CSS
.card { border: 3px solid #cbd5e1; }
.card:has(> img)     { border-color: #2563eb; }
.card:not(:has(img)) { border-style: dashed; }
HTML
<div class="card" id="one"><img alt="" src="…"><p>Direct image</p></div>
<div class="card" id="two"><figure><img alt="" src="…"></figure><p>Image in a figure</p></div>
<div class="card" id="three"><p>No image</p></div>

What border does each card get?

Show answer

Card one: blue and solid. Card two: grey and solid. Card three: grey and dashed. :has() matches an element by what's inside it, and its argument is a relative selector: > img means a direct child image, so only card one turns blue. Card two has an image, but deeper, so it isn't blue, and it isn't dashed either because plain :has(img) looks at all descendants. Card three has no image at all, so :not(:has(img)) matches.

Three cards
CSS
.row  { display: flex; gap: 8px; }
.card { width: 120px; padding: 6px; border: 3px solid #cbd5e1; }
.card:has(> img)     { border-color: #2563eb; }
.card:not(:has(img)) { border-style: dashed; }
.card img { display: block; width: 40px; height: 24px; }
.card figure { margin: 0; }
.card p { margin: 4px 0 0; font-size: 13px; }
HTML
<div class="row">
  <div class="card" id="one"><img alt="" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 24'%3E%3Crect width='40' height='24' fill='%2393c5fd'/%3E%3C/svg%3E"><p>Direct image</p></div>
  <div class="card" id="two"><figure><img alt="" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 24'%3E%3Crect width='40' height='24' fill='%2393c5fd'/%3E%3C/svg%3E"></figure><p>Image in a figure</p></div>
  <div class="card" id="three"><p>No image</p></div>
</div>
Resultlive, in your browser
What’s happening
  1. .card:has(> img) is read as "a .card that has an img as its direct child". Card one's image is a direct child, so its border is blue (rgb(37, 99, 235)).
  2. Card two's image sits inside a <figure>, so > img doesn't match from the card, and the border stays grey. It still contains an image, so :not(:has(img)) doesn't match either: solid.
  3. Card three has no image anywhere inside, so :has(img) is false, :not() flips it, and the border is dashed.
  4. :has() takes the specificity of its argument, like :is(), and it's Baseline since late 2023. It also reaches siblings: h2:has(+ p) styles a heading followed by a paragraph, the "previous sibling" selector CSS never had.

Learn more: :is(), :where(), :not() and :has().

Open in topic →

Predict: logical properties in right-to-left text

CSS
.tag { margin-inline-start: 20px; border-inline-start: 4px solid #2563eb; }
HTML
<p dir="ltr"><span class="tag">English</span></p>
<p dir="rtl"><span class="tag">عربي</span></p>

Which physical side gets the margin and the border in each paragraph?

Show answer

The left side in the LTR paragraph and the right side in the RTL one. Logical properties are relative to the writing direction: the inline axis runs the way text runs, and inline-start is where a line begins. In right-to-left text a line begins on the right, so the same rule mirrors the component with no extra CSS. That's why new code should prefer margin-inline-start over margin-left.

The same rule in both directions
CSS
.tag { display: inline-block; padding: 2px 8px; background: #e0e7ff; margin-inline-start: 20px; border-inline-start: 4px solid #2563eb; }
HTML
<p dir="ltr"><span class="tag" id="ltr">English</span></p>
<p dir="rtl"><span class="tag" id="rtl">عربي</span></p>
Resultlive, in your browser
What’s happening
  1. In the LTR paragraph, inline-start is the left, so the computed margin-left is 20px and border-left-width 4px; the right side gets nothing.
  2. dir="rtl" sets direction: rtl, which is inherited by the span. Now a line starts on the right, so the same declarations compute to margin-right: 20px and border-right-width: 4px.
  3. The span also lines up from the right in RTL, 20px in from the paragraph's right edge, which the test measured.
  4. The mirror is free because the browser maps logical to physical per element when it computes styles. Note that four-value shorthands like margin: 0 0 0 20px and inset stay physical.

Learn more: Logical properties.

Open in topic →

Explain: 100vh on phones

"Why does a height: 100vh hero get cut off on a phone, and what do you use instead?"

Show answer

Because on mobile there are two viewport heights, and vh means the larger one. The browser's address bar shows on load and retracts as you scroll, so lvh is the height with the UI retracted, svh with it shown, and dvh whatever is visible right now. Plain vh equals lvh, so a 100vh hero is taller than the screen on load and its bottom is hidden behind the toolbar. I use 100svh for things that must fit on load, 100dvh for app-like full-height layouts, and keep vh or lvh for backgrounds.

What’s happening
  1. On a phone, the visible area changes as the browser UI collapses. If vh followed it, every vh layout would relayout and jump during scrolling, so browsers made vh the large, stable value.
  2. 100svh is the small viewport: guaranteed visible with the UI showing. A hero at 100svh fits on first load, with a gap at the bottom once the toolbar retracts.
  3. 100dvh tracks the current size, so it's always exactly the visible area, at the cost of layout work while the UI animates. That's the right trade-off for chat apps or full-screen tools.
  4. The units can't be shown in this page's demos: on a desktop browser, and in the headless Chrome the tests use, the small, large and dynamic viewports are all the same size. Test them on a real phone or in device emulation.

Learn more: Viewport units on phones and The viewport meta tag.

Open in topic →

Explain: srcset and sizes

HTML
<img src="photo-800.jpg"
     srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
     sizes="(width >= 900px) 50vw, 100vw"
     width="1600" height="900" alt="Harbour at dusk">

"How does the browser decide which file to download?"

Show answer

It works out the slot width from sizes, multiplies by the device pixel ratio, and picks the smallest candidate that covers it. srcset with w descriptors only lists files and their real widths; sizes tells the browser how wide the image will be displayed, because it chooses the file before the CSS has been applied. On a 390px phone at 3× that's 100vw × 3 = 1170 pixels, so it fetches photo-1600.jpg; on a 1200px laptop at 1× it's 50vw = 600 pixels, so photo-800.jpg. The browser is allowed to pick differently, for example a smaller file on a slow connection or one it already has in cache.

What’s happening
  1. sizes is a list of media conditions and lengths, checked in order: at 900px and wider the image is half the viewport, otherwise the full width. Without sizes, the browser assumes 100vw, which over-downloads for images in narrow columns.
  2. The browser multiplies the chosen length by the pixel ratio to get the pixels it needs, then picks a candidate from srcset whose w value is enough.
  3. width and height don't pick a file; they give the box its aspect ratio before anything loads, so the layout doesn't shift when the image arrives.
  4. For different crops at different sizes (art direction) or for format fallbacks like AVIF, use <picture> with <source media> or <source type>; the inner <img> is still required and carries alt.
  5. A live demo can't show this choice reliably: which file is picked depends on the device's pixel ratio and the browser's own heuristics, so check it in DevTools' Network panel with device emulation.

Learn more: Responsive images and Images, figure and media.

Open in topic →

Explain: reflow vs repaint

CSS
.a { width: 300px; }               /* change 1 */
.b { color: crimson; }             /* change 2 */
.c { transform: translateX(20px); } /* change 3 */
.d { opacity: 0.5; }               /* change 4 */

"Which of these changes make the browser recalculate layout, which only repaint, and which can skip both?"

Show answer

Changing width needs layout, then paint and composite; color needs only paint and composite; transform and opacity on an element with its own compositor layer need only compositing. Layout (reflow) recalculates geometry, and because boxes affect each other, one change can move many elements. Paint redraws pixels without moving anything. Compositing just moves or blends already-painted layers, often on the GPU and off the main thread, which is why transform and opacity are what you animate.

What’s happening
  1. Every change starts with style recalculation: the browser works out which elements' computed values changed.
  2. width is geometric: the element's box changes, its children re-wrap and its siblings move. So layout runs, then everything it moved has to be repainted and composited. margin, padding, top/left, font-size and adding DOM nodes are in the same group.
  3. color (and background-color, box-shadow, outline) changes pixels but no geometry, so layout is skipped and only paint and composite run.
  4. transform and opacity don't affect layout at all. If the element is on its own layer (animated ones are promoted, or will-change asks for it), the compositor just redraws the frame with the layer moved or faded.
  5. What makes reflow expensive in practice is forcing it from JavaScript: reading offsetHeight or getBoundingClientRect() right after a style write runs layout synchronously, and doing that in a loop is layout thrashing.

Learn more: Reflow and repaint and The rendering pipeline.

Open in topic →

Predict: which nudge moves the neighbour?

CSS
.row > div { width: 60px; height: 40px; }
.t { transform: translateX(100px); }
.r { position: relative; left: 100px; }
.m { margin-left: 100px; }
HTML
<div class="row"><div class="t"></div><div class="next"></div></div>
<div class="row"><div class="r"></div><div class="next"></div></div>
<div class="row"><div class="m"></div><div class="next"></div></div>

Each row is a flex row. In which rows does .next move? And what do offsetLeft and getBoundingClientRect() report for the shifted box?

Show answer

Only the margin row moves its neighbour. transform and position: relative both paint the box 100px to the right without changing its place in layout, so .next stays put. margin-left changes the layout itself, so the box and everything after it moves. offsetLeft reports the layout position, so it ignores the transform but includes the relative offset; getBoundingClientRect() reports where the box is drawn, so it shows all three shifts. Animate transform for exactly this reason: no layout work per frame.

Three ways to shift a box by 100px
CSS
.row { display: flex; height: 40px; margin-bottom: 8px; }
.row > div { width: 60px; height: 40px; background: #93c5fd; }
.row > .next { background: #fde68a; }
.t { transform: translateX(100px); }
.r { position: relative; left: 100px; }
.m { margin-left: 100px; }
HTML
<div class="row"><div class="t"></div><div class="next" id="nt"></div></div>
<div class="row"><div class="r"></div><div class="next" id="nr"></div></div>
<div class="row"><div class="m"></div><div class="next" id="nm"></div></div>
Resultlive, in your browser
What’s happening
  1. All three blue boxes are drawn 100px from their row's left edge: getBoundingClientRect() measures the rendered box, after transforms and relative offsets.
  2. With transform, the layout still has the box at 0, so .next sits at 60px and offsetLeft says 0. The transform is applied at paint and composite time, which is why animating it doesn't run layout.
  3. With position: relative; left: 100px, the box keeps its layout slot too (.next at 60px), but the offset is part of positioning, so offsetLeft includes it: 100. Animating left still runs layout every frame, even though nothing else moves.
  4. With margin-left, the box's slot itself is 100px further right, so .next follows to 160px. Animating margins reflows the whole row every frame.
  5. will-change: transform can promote the box to its own layer before an animation starts, but each layer costs memory and it creates a stacking context and a containing block for fixed children, so add it just before animating and remove it after.

Learn more: Animating cheaply and Transforms.

Open in topic →

Explain: what blocks the first paint?

HTML
<head>
  <link rel="stylesheet" href="app.css">
  <link rel="stylesheet" href="print.css" media="print">
  <style>@import url("fonts.css");</style>
  <script src="app.js"></script>
</head>

"What delays the first paint here, and how would you fix it?"

Show answer

app.css, the @import chain and the plain script all delay it; print.css doesn't. A stylesheet link whose media matches is render-blocking, so the page isn't painted until it's downloaded and parsed; one with media="print" downloads at low priority without blocking. @import is only discovered after the file containing it is parsed, so it adds a round trip in series. A classic script in the head blocks the parser and also waits for the stylesheets before it runs. I'd inline the critical CSS, turn @import into a <link> (or preload), add defer to the script, and give fonts font-display: swap with a preload for the one the first screen needs.

What’s happening
  1. app.css matches every medium, so it's render-blocking: no pixels until it arrives. Keeping the critical CSS small, or inlining the part the first screen needs, shortens that wait.
  2. print.css has media="print", which doesn't match a screen, so the browser fetches it without holding up rendering. The same trick works for stylesheets for wide screens only (media="(width >= 1000px)").
  3. The @import inside <style> can only start downloading fonts.css once that style block is parsed, and anything fonts.css imports waits again. Separate <link> tags download in parallel.
  4. <script src="app.js"> without defer stops the parser while it downloads and runs, and it won't run until the stylesheets above it have loaded, because it might read styles. defer removes both waits.
  5. Fonts are the second wait: text in a web font can't be drawn until it arrives. font-display: swap shows a fallback first; a fallback with matched metrics (size-adjust) keeps the swap from shifting layout. Measure with Lighthouse or the Performance panel rather than guessing.

Learn more: Loading performance and defer and async.

Open in topic →

Predict: what is each button called?

HTML
<button id="a" aria-label="Close dialog">✕</button>
<button id="b"><svg aria-hidden="true">…</svg></button>
<button id="c"><svg aria-hidden="true">…</svg><span class="visually-hidden">Delete</span></button>
<button id="d" aria-labelledby="t">Save</button> <span id="t" hidden>Save draft</span>
<button id="e" title="Settings"><svg aria-hidden="true">…</svg></button>

What accessible name does a screen reader announce for each button?

Show answer

"Close dialog", nothing, "Delete", "Save draft" and "Settings". The name computation takes the first source that produces text: aria-labelledby, then aria-label, then the element's content (for buttons and links), then title as a last resort. aria-label replaces the ✕ text; an icon hidden with aria-hidden contributes nothing, so button B is an unnamed button; visually hidden text still counts; aria-labelledby can point at hidden text and wins over the visible "Save"; and title names E, though it's a weak fallback that touch and keyboard users never see.

Five buttons, five names
CSS
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
button { min-width: 36px; height: 32px; margin-right: 6px; }
svg { width: 16px; height: 16px; vertical-align: middle; }
HTML
<button id="a" aria-label="Close dialog">✕</button>
<button id="b"><svg aria-hidden="true" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6" fill="#64748b"/></svg></button>
<button id="c"><svg aria-hidden="true" viewBox="0 0 16 16"><rect x="3" y="3" width="10" height="10" fill="#dc2626"/></svg><span class="visually-hidden">Delete</span></button>
<button id="d" aria-labelledby="t">Save</button> <span id="t" hidden>Save draft</span>
<button id="e" title="Settings"><svg aria-hidden="true" viewBox="0 0 16 16"><circle cx="8" cy="8" r="4" fill="#2563eb"/></svg></button>
Resultlive, in your browser
What’s happening
  1. A: aria-label comes before content in the computation, so the ✕ character is ignored and the name is "Close dialog". Good for icon buttons, but if the button showed a visible word, aria-label should contain it (Label in Name, for voice control).
  2. B: the only content is an SVG with aria-hidden="true", which removes it from the accessibility tree, so the name is empty. A screen reader says just "button": the most common failure on icon-only buttons.
  3. C: the same icon plus a visually hidden span. That span is clipped to 1px but still in the accessibility tree, so its text becomes the name, "Delete".
  4. D: aria-labelledby is the first step and it reads the referenced element's text even when that element is hidden (display: none), so the visible "Save" is replaced by "Save draft". Powerful, and easy to get out of sync with what sighted users see.
  5. E: no labelledby, no label, no content text, so the computation falls through to title: "Settings". It works for screen readers, but the tooltip only shows on mouse hover, so prefer visible text or a visually hidden label.

Learn more: Accessible names and descriptions and Hiding content.

Open in topic →

Explain: :focus vs :focus-visible

CSS
button:focus { outline: none; }                    /* the designer's request */
:focus-visible { outline: 3px solid #2563eb; outline-offset: 2px; }

"The designer wants no focus ring when people click buttons. What's wrong with outline: none, and what do you do instead?"

Show answer

outline: none on :focus removes the ring for keyboard users too, which fails WCAG 2.4.7 (Focus Visible). :focus matches any focused element, including a button just clicked with the mouse. :focus-visible matches only when the browser decides a ring is useful: after keyboard navigation, and always for text inputs. So I drop the outline: none and style rings with :focus-visible: mouse users don't see a ring on buttons, keyboard users always do.

A text input always shows the ring
CSS
input, button { margin-right: 8px; }
:focus-visible { outline: 3px solid #2563eb; outline-offset: 2px; }
HTML
<input id="name" aria-label="Name"> <button id="save">Save</button>
Resultlive, in your browser
What’s happening
  1. :focus matches whenever an element has focus, however it got there. Removing the outline there hides the indicator from everyone, and keyboard users then can't see where they are on the page.
  2. :focus-visible uses the browser's heuristics: a text field always gets it, because you need to see where you're typing; a button gets it after Tab but not after a mouse click. The test focused the input from script and it matched, with the 3px solid ring applied.
  3. The mouse-click case can't be proven here (the test can't make a real pointer click), so try it in the live result: Tab to the Save button and the ring appears; click it with the mouse and Chrome normally doesn't show one.
  4. A good ring has at least 3:1 contrast against what's around it and an offset so it doesn't merge with the border. Use outline rather than only box-shadow, because forced-colours mode removes shadows.

Learn more: Visible focus and Keyboard access and focus order.

Open in topic →

Predict: what does this ARIA actually do?

HTML
<h2 id="h" role="button">Shipping details</h2>
<div id="d" role="button">Pay now</div>
<button id="b" aria-hidden="true">Menu</button>

For each element: what role and name does it expose, and can a keyboard user focus it?

Show answer

The heading is now a button and no longer a heading, and it can't be focused; the div is announced as "Pay now", button, but can't be focused or activated by keyboard; the aria-hidden button has no name for screen readers but can still be focused. An explicit role replaces the element's native semantics; it doesn't add behaviour. And aria-hidden on something focusable creates a control that keyboard users land on while the screen reader says nothing useful. Each of these is fixed by using native HTML: a <button> inside the <h2>, a real <button> for Pay now, and hidden or inert when the menu button really should be gone.

Roles, names and focus
HTML
<h2 id="h" role="button">Shipping details</h2>
<div id="d" role="button">Pay now</div>
<button id="b" aria-hidden="true">Menu</button>
Resultlive, in your browser
What’s happening
  1. role="button" on the <h2> replaces the heading role, so the page loses a heading that screen-reader users navigate by, and gains a "button" that Tab can't reach (focus() failed) and Enter does nothing on. Two failures from one attribute.
  2. The div gets the right announcement, "Pay now, button", but ARIA added no behaviour: no tab stop, no Enter or Space, no form submission. That's the "looks fine in the accessibility tree, broken for the keyboard" case automated tools often miss.
  3. The aria-hidden button is removed from the accessibility tree (its name is empty), but it's still in the tab order: focus() succeeded. A keyboard user lands on it and hears nothing meaningful.
  4. The first rule of ARIA covers all three: use the native element. <h2><button aria-expanded="false">Shipping details</button></h2> keeps the heading and gives a real button; for content that should be hidden from everyone, use hidden, inert or display: none.

Learn more: The first rule of ARIA and ARIA roles, states and properties.

Open in topic →

Predict: which pairs pass WCAG AA?

CSS
.p1 { color: #767676; background: #fff; font-size: 16px; }
.p2 { color: #777777; background: #fff; font-size: 16px; }
.p3 { color: #949494; background: #fff; font-size: 24px; }
.p4 { color: #fff;    background: #2563eb; font-size: 16px; }

Which of these text styles pass WCAG 2.2 level AA contrast?

Show answer

.p1, .p3 and .p4 pass; .p2 fails. AA needs 4.5:1 for normal text and 3:1 for large text (24px, or about 18.66px bold). #767676 on white is 4.54:1, just over; #777777 is 4.48:1, just under, even though you can't see the difference. #949494 at 24px only needs 3:1 and has 3.03:1. White on #2563eb is 5.17:1. The ratio is (lighter luminance + 0.05) / (darker + 0.05), so check it with a tool, not by eye.

Contrast computed from the rendered colours
CSS
p { margin: 4px 0; padding: 4px 8px; }
.p1 { color: #767676; background: #fff; font-size: 16px; }
.p2 { color: #777777; background: #fff; font-size: 16px; }
.p3 { color: #949494; background: #fff; font-size: 24px; }
.p4 { color: #fff;    background: #2563eb; font-size: 16px; }
HTML
<p class="p1">Normal text, #767676</p>
<p class="p2">Normal text, #777777</p>
<p class="p3">Large text, #949494</p>
<p class="p4">White on blue</p>
Resultlive, in your browser
What’s happening
  1. Each colour is converted to relative luminance: channels are linearised (the sRGB curve) and weighted 0.2126 red, 0.7152 green, 0.0722 blue, because eyes are most sensitive to green. The test did this with the computed colours.
  2. #767676 on white comes out at 4.54:1, the lightest grey that passes for body text. One step lighter, #777777, is 4.48:1 and fails: AA is a hard threshold, there's no rounding up.
  3. .p3 is 24px, which counts as large text, so its threshold is 3:1, and #949494 passes at 3.03:1. The same colour at 16px would fail.
  4. White on #2563eb is 5.17:1, a pass for any size. The same 3:1 minimum also applies to non-text things that matter, like input borders, icons and focus rings, and colour must never be the only way information is shown.

Learn more: Colour contrast and not relying on colour alone.

Open in topic →

Predict: which links can Tab reach?

CSS
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
HTML
<a id="skip" class="visually-hidden" href="#main">Skip to content</a>
<a id="gone" href="/old" style="display: none">Old page</a>
<a id="ghost" href="/help" aria-hidden="true">Help</a>
<a id="faded" href="/new" style="opacity: 0">New</a>

Which links does a keyboard user reach, and which does a screen reader announce?

Show answer

Tab reaches skip, ghost and faded; a screen reader announces skip and faded. The visually hidden skip link is out of sight but fully present: focusable and announced (a skip link should then become visible on focus). display: none removes the link from everything. aria-hidden removes it only from the accessibility tree, so it's still a tab stop that announces nothing, a bug. opacity: 0 hides nothing from the keyboard or the screen reader, only from the eyes.

Four hidden links
CSS
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
a { margin-right: 10px; }
HTML
<a id="skip" class="visually-hidden" href="#main">Skip to content</a>
<a id="gone" href="/old" style="display: none">Old page</a>
<a id="ghost" href="/help" aria-hidden="true">Help</a>
<a id="faded" href="/new" style="opacity: 0">New</a>
Resultlive, in your browser
What’s happening
  1. The skip link uses the visually hidden pattern: a 1px clipped box, but still rendered, so it's focusable and its name "Skip to content" is in the tree. Skip links normally add a :focus-visible rule that brings them on screen when tabbed to.
  2. display: none removes the box, so the link is neither focusable nor named. The same goes for the hidden attribute and visibility: hidden.
  3. aria-hidden="true" leaves the link visible and focusable but removes it from the accessibility tree, so its name is empty: a screen-reader user tabs onto something silent. Never put aria-hidden on a focusable element or its ancestor; use inert if a whole region should be unreachable.
  4. opacity: 0 changes only painting: the link is focusable and announced as "New" while being invisible, which confuses both sighted keyboard users and screen-reader users.

Learn more: Hiding content and Keyboard access and focus order.

Open in topic →

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.