HTML & CSS quick reference for interviews

The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.

HTML document and semantics

Document base.
<!DOCTYPE html> turns on standards mode; without it the browser falls back to quirks mode. <html lang="en"> helps screen readers, hyphenation and translation. Without <meta name="viewport" content="width=device-width, initial-scale=1"> phones render the page about 980px wide and zoom out.
Semantic elements.
header, nav, main, article, section, aside, footer describe the role of a part of the page and become landmarks for screen readers. A page has one visible main. article is self-contained content, section is a thematic group with a heading.
Headings.
h1-h6 build the page outline that screen reader users navigate by. Don't skip levels and don't pick a level for its size: size is set in CSS.
Block and inline.
div is a block: it takes the full width and starts a new line. span is inline: it ignores width, height and vertical margins. inline-block flows with text but accepts sizes.
Meaning, not look.
strong and em mark importance and stress, b and i only change the look. a with href navigates, button performs an action. table is for tabular data, dl for term and description pairs, figure with figcaption for an illustration with a caption.
Attributes.
id is unique on the page, class can repeat. data-user-id is read in JavaScript as el.dataset.userId. A block element like div inside p is invalid: the parser closes p before it.

Forms

label.
<label for="email"> linked to the field's id, or wrapping the field: a click focuses the field and screen readers read its name. placeholder is not a label: it disappears while typing and usually has low contrast.
Buttons.
Inside a form a <button> defaults to type="submit". Any other button needs type="button", or it submits the form.
Sending data.
GET puts fields into the URL query string, POST into the request body. An unchecked checkbox isn't sent at all. Fields without name aren't sent either.
Groups.
Radio buttons of one question share a name and are wrapped in fieldset with a legend that names the question.
Validation.
required, type="email", pattern, min and max are checked by the browser. :user-invalid highlights errors only after the user has interacted, unlike :invalid, which fires on an empty form at once.
Errors.
The message is linked to the field with aria-describedby, and the field gets aria-invalid="true". Then a screen reader reads the error together with the field.

Box model

Box.
Content, padding, border, margin. Padding is inside the border and gets the background, margin is outside and stays transparent.
box-sizing.
With border-box, width includes padding and border, so a 200px block stays 200px. The common reset sets it on *, *::before, *::after.
Margin collapsing.
Adjacent vertical margins of blocks merge into the larger one: 20px and 30px give 30px, not 50px. A parent and its first child collapse too if the parent has no padding, border or its own BFC. Flex and grid items never collapse.
Shorthands.
margin: 10px 20px is vertical then horizontal. Four values go clockwise from the top: top, right, bottom, left.
overflow.
auto shows scrollbars only when needed, scroll always. hidden clips but the box can still be scrolled by script; clip clips without creating a scroll container, so sticky inside keeps working.
BFC.
A block formatting context contains floats and stops margins collapsing through it. The clean way to create one is display: flow-root; overflow other than visible, flex and grid items also create one.
Centering a block.
A block with a width is centered with margin-inline: auto. text-align: center centers only inline content inside the block.

Cascade, specificity and inheritance

Cascade order.
First origin and !important, then cascade layers, then specificity, then source order: the later rule wins. Inline style beats any selector, !important in a stylesheet beats inline style.
Specificity.
Counted as (ids, classes + attributes + pseudo-classes, types + pseudo-elements) and compared left to right. #nav a is (1,0,1) and beats .menu .item a.link at (0,3,1).
:is, :not, :has, :where.
:is(), :not() and :has() take the specificity of their most specific argument. :where() always adds zero, which makes it good for base styles that are easy to override.
Inheritance.
Text properties are inherited: color, font-*, line-height, visibility. Box properties are not: margin, border, background, width.
initial, inherit, unset.
initial is the value from the spec, not the browser default. inherit takes the parent's value. unset acts as inherit for inherited properties and as initial for the rest.
@layer.
Among normal styles, a later declared layer beats an earlier one regardless of specificity, and styles outside any layer beat all layers. Putting resets and libraries into early layers removes specificity wars.
Combinators.
.menu a matches any descendant, .menu > a only direct children, h2 + p the paragraph right after h2, h2 ~ p all following sibling paragraphs.
@layer reset, vendor, components;

@import url("datepicker.css") layer(vendor);

@layer components {
  .button { padding: 0.5rem 1rem; }
}

/* outside layers: wins over all of them */
.button.danger { background: crimson; }

Positioning and stacking

relative.
Shifts the element visually, but its original place in the flow stays reserved. It also becomes the reference for absolutely positioned children.
absolute.
Taken out of the flow and positioned against the nearest ancestor whose position isn't static. inset: 0 stretches it over that ancestor.
fixed.
Positioned against the viewport. An ancestor with transform, filter or perspective becomes its containing block, and the element scrolls with that ancestor.
sticky.
Behaves like relative until it reaches the top offset, then sticks inside its parent. It doesn't stick if an ancestor has overflow: hidden or auto, or if the parent is no taller than the element.
z-index.
Works on positioned elements and on flex and grid items. Values are compared only within one stacking context.
Stacking context.
Created by positioned elements with z-index, opacity below 1, transform, filter, will-change and isolation: isolate. A child with z-index: 9999 can't rise above a neighbor of its parent's context. isolation: isolate on a component root keeps its layers inside.

Flexbox

Axes.
justify-content aligns along the main axis set by flex-direction, align-items along the cross axis. In flex-direction: column, justify-content: center centers vertically.
flex: 1.
Expands to flex: 1 1 0%: grow, shrink, basis 0. Items share the free space equally regardless of content. In a row, flex-basis takes priority over width.
Spacing.
gap sets space between items without extra space after the last one. flex-wrap: wrap moves items that don't fit to the next line. margin-left: auto pushes an item and everything after it to the right.
Equal height.
By default align-items: stretch makes items in a row as tall as the tallest one.
min-width: auto.
A flex item doesn't shrink below its content, so a long word or text-overflow: ellipsis stretches the row. min-width: 0 on the item fixes it. flex-shrink: 0 keeps an icon from being squeezed.
order.
Changes only the visual order. Keyboard focus and screen readers follow the DOM, so a big mismatch confuses users.
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.navbar { display: flex; gap: 1rem; }
.navbar .logout { margin-left: auto; }

.row-item { flex: 1; min-width: 0; }
.row-item .title {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

Grid

Tracks.
grid-template-columns: repeat(3, 1fr) gives three equal columns; fr is a share of the free space. 250px 1fr is a fixed sidebar and content filling the rest.
Placement.
grid-column: 1 / -1 stretches an item across all columns. grid-template-areas names regions, and items take them with grid-area.
auto-fill and auto-fit.
With minmax(200px, 1fr) both fit as many columns as possible. auto-fill keeps empty tracks, auto-fit collapses them, so a few items stretch to the full width.
Implicit grid.
Items beyond the defined tracks create new rows automatically. Their size is set by grid-auto-rows. grid-auto-flow: dense fills gaps, but the visual order can then differ from the DOM.
Alignment.
place-items: center is align-items and justify-items in one: each item is centered in its cell.
subgrid.
grid-template-rows: subgrid lets a nested grid use the parent's tracks, so titles, text and buttons of neighboring cards line up.
Grid or Flexbox.
Grid lays out in two dimensions by a predefined scheme: page layout, card grids. Flexbox lays out a single row or column by content size: toolbars, button groups.
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.page {
  display: grid;
  grid-template-columns: 250px 1fr;
  grid-template-areas: "side main";
}

Units and responsive design

em and rem.
rem is relative to the root font size, em to the element's own font size (to the parent's for font-size itself), so em compounds in nested elements. % is relative to the containing block.
Viewport units.
50vw is half the viewport width. On phones 100vh includes the area under the browser bars: use 100dvh, or svh and lvh for the smallest and largest heights.
clamp().
clamp(1rem, 2.5vw, 2rem) on a 1000px screen is 25px, within 16-32px. Fluid type with a rem part, like clamp(1rem, 0.9rem + 1vw, 1.5rem), still follows the user's font size.
Media queries.
Mobile first: base styles for small screens, @media (min-width: 48em) adds more. The range syntax @media (width >= 768px) is shorter. Breakpoints in em follow the user's font settings.
Container queries.
container-type: inline-size on the parent and @container (min-width: 400px) on the component: it adapts to the space it's placed in, not to the screen. cqi is 1% of the container's width.
User preferences.
@media (hover: hover) for hover effects only on devices with a mouse, prefers-reduced-motion to turn off animations, prefers-color-scheme for the dark theme.
Logical properties.
margin-inline-start, padding-block, inset-inline-end follow the writing direction, so an RTL layout (Arabic, Hebrew) mirrors without separate styles.
.grid { display: grid; gap: 1rem; }

@media (width >= 48em) {
  .grid { grid-template-columns: 1fr 1fr; }
}

.card-wrap { container-type: inline-size; }

@container (min-width: 400px) {
  .card { display: flex; }
}

Images and media

Base rule.
img { max-width: 100%; height: auto; } keeps images inside the container without distorting them.
srcset and sizes.
srcset lists files of different widths, sizes tells how wide the image will be on screen. The browser picks the file for the screen and pixel density.
picture.
Needed for art direction (a different crop on phones) or for formats with a fallback: source with AVIF or WebP, then a JPEG img.
Loading.
loading="lazy" defers images below the fold. The main hero image gets fetchpriority="high" instead and isn't lazy.
Sizing.
object-fit: cover fills the box and crops the rest, object-position: top chooses which part stays. aspect-ratio: 16 / 9 keeps the proportions of a video container.
Gap under img.
An image is inline and sits on the text baseline, leaving space for descenders. display: block or vertical-align: middle removes it.
img or background.
Content images go in img with alt: they're indexed and read aloud. Decorative backgrounds and patterns go in background-image.

Modern CSS

Custom properties.
--brand: #4f46e5 and color: var(--brand, black). Unlike Sass $variables, they exist at runtime: they inherit through the DOM, change in media queries and from JavaScript.
:has().
A parent selector: .card:has(img) is a card containing an image, .field:has(input:invalid) a field with an error. :focus-within matches an element with focus inside.
Nesting.
Native nesting with & works without a preprocessor: .card { &:hover { ... } .title { ... } }.
Colors.
oklch() has perceptually even lightness, so a palette of shades is easy to build. color-mix(in oklch, var(--brand) 80%, white) mixes colors. #3366ff80 has 80 as alpha, about 50%.
Themes.
color-scheme: light dark switches form controls and scrollbars. light-dark(#111, #eee) picks a value for the current scheme. currentColor reuses the text color for borders and icons.
Feature checks.
@supports (display: grid) applies styles only where the property is supported. @property declares a typed variable that can be animated.
New building blocks.
The popover attribute and <dialog> give top-layer popups, @starting-style animates appearance from display: none, View Transitions animate between states, anchor positioning attaches a tooltip to its trigger, text-wrap: balance evens out heading lines.

Tailwind CSS

Utility-first.
Styles are built from small classes right in the markup: flex, p-4, text-sm. No class names to invent and no dead CSS. The spacing step is 0.25rem, so p-4 is 1rem.
Variants.
md:flex applies from the md breakpoint up (mobile first). hover:, focus-visible:, disabled:. dark: follows prefers-color-scheme by default in v4.
group and peer.
group on a parent and group-hover: on a child style the child when the parent is hovered. peer and peer-checked: style an element by the state of its sibling. data-[state=open]: styles by a data attribute.
Arbitrary values.
w-[37px], bg-[#1da1f2], grid-cols-[200px_1fr] for values outside the theme.
Full class names.
Tailwind finds classes by scanning source files as text, so bg-${color}-500 isn't generated. Keep full names in a map: { red: "bg-red-500" }.
v4.
Configured in CSS: @import "tailwindcss" and @theme { --color-brand: ... } create bg-brand, text-brand and so on. Sources are detected automatically. A class-based dark theme: @custom-variant dark (&:where(.dark, .dark *)).
Merging classes.
When a component takes outside classes, conflicts like p-2 and p-4 are resolved by tailwind-merge. @apply is for rare cases like third-party markup, otherwise it brings back the problems of plain CSS.

Accessibility

Native first.
button, a, label, dialog already have a role, focus and keyboard handling. ARIA is for cases with no native element. A div with role="button" also needs tabindex="0" and Enter and Space handlers.
Focus.
:focus-visible shows the ring for keyboard users and not on mouse clicks. Never remove outline without a replacement. tabindex="0" adds an element to the tab order, -1 makes it focusable only from script, positive values break the order.
Hiding.
display: none hides from everyone. aria-hidden="true" hides only from screen readers: for decorative icons. A sr-only class hides visually but keeps the text for screen readers.
alt.
A decorative image gets an empty alt="". An icon-only link describes its destination: alt="Home", not alt="house icon". aria-label is for controls with no visible text.
WCAG.
Level AA is the usual target: 4.5:1 contrast for normal text, 3:1 for large text, targets at least 24 by 24 px (WCAG 2.2). A is the minimum, AAA the strictest.
Dialogs and SPAs.
dialog.showModal() traps focus, closes on Esc and makes the rest of the page inert. After navigation in an SPA, move focus to the new heading or announce the change with aria-live.
Landmarks and skip link.
header, nav, main, footer let screen reader users jump between regions. A skip link at the start of the page moves keyboard focus straight to main.
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}

Rendering and performance

Pipeline.
Style, layout, paint, composite. Changing width or left goes through all steps; transform and opacity need only compositing, so they animate smoothly at 60 FPS.
Layout thrashing.
Reading offsetHeight or getBoundingClientRect() right after changing styles forces a synchronous layout. In a loop it repeats every time: read everything first, then write.
Hints.
will-change: transform only right before an animation and on a few elements: each one takes memory. contain: content and content-visibility: auto let the browser skip work for isolated or offscreen parts.
Core Web Vitals.
LCP (loading the main content), INP (response to input), CLS (layout shifts). Lighthouse gives lab data from one run, CrUX and RUM give field data from real users.
Avoiding CLS.
width and height or aspect-ratio on images and embeds, reserved space for banners, font-display: swap with a fallback font tuned by size-adjust.
CSS delivery.
Critical CSS for the first screen is inlined, the rest loads normally. @import inside CSS loads files one after another. Content hashes in file names (app.3f9a1c.css) allow long caching.
Scripts and hints.
defer runs scripts in order after parsing, async runs each as soon as it loads. preload fetches a resource for the current page with high priority, prefetch one for the next page at low priority.

Common pitfalls

  • outline: none without a replacement focus style leaves keyboard users without a visible focus.
  • z-index: 9999 doesn't help if the parent has transform or opacity: they create a stacking context.
  • position: sticky doesn't stick under an ancestor with overflow: hidden or auto.
  • position: fixed inside an element with transform is positioned against that element, not the viewport.
  • A long word or text-overflow: ellipsis in a flex item stretches the row: add min-width: 0 to the item.
  • height: 100vh on phones is taller than the visible area: use 100dvh.
  • A <button> inside a form without type submits the form.
  • ::before and ::after don't render without content, even an empty content: "". They don't work on img and input at all.
  • width and height on an inline element like span have no effect.
  • Tailwind doesn't generate classes built from strings: bg-${color}-500 never reaches the CSS.
  • transition: all also animates properties you didn't plan to, including expensive layout ones.
  • placeholder instead of label: the hint disappears while typing and screen readers may not read it as the field's name.

Cheat sheet