Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 77 ยท Web and Frontend Interview Questions

HTML and CSS Interview Questions

Prepare HTML and CSS interview answers on semantics, accessibility, the box model, specificity, flexbox versus grid and stacking contexts with live demos.

HTML and CSS questions look easy until the follow-up arrives. "What is the box model?" becomes "Why is my element wider than I set it?". "What is z-index?" becomes "Why does z-index: 9999 not work?". Interviewers use these topics to check whether you understand the rules or only know how to copy snippets.

This lesson pairs short model answers with live examples you can edit. Deeper coverage lives in Semantic Elements, Accessibility, ARIA, The Box Model, Specificity, Flexbox vs Grid and z-index.

Semantics and accessibility

Q: What is semantic HTML, and why does it matter? Choosing elements for their meaning, not their looks: <header>, <nav>, <main>, <article>, <button>, <h1>โ€“<h6>, <ul>, <label>. Browsers, search engines and assistive technology use that meaning. A <button> is focusable, activates with Enter and Space, and is announced as a button for free. A <div> with a click handler has none of that until you rebuild it by hand.

HTML
<!-- Weak: looks fine, but a keyboard cannot reach it and a screen reader says nothing useful -->
<div class="btn" onclick="save()">Save</div>

<!-- Better: the browser provides focus, keyboard activation and the role -->
<button type="button" onclick="save()">Save</button>

Q: How do you make a page accessible? Start with native elements, then add what is missing:

  • Text alternatives: meaningful alt on informative images, empty alt="" on decorative ones.
  • Every form control has a visible <label> connected with for/id (or wrapping it).
  • One <h1>, headings in a logical order, landmarks (<nav>, <main>) so users can jump around.
  • Everything works with the keyboard, and the focus indicator stays visible.
  • Sufficient contrast (WCAG AA asks for at least 4.5:1 for normal text and 3:1 for large text), and information is never conveyed by color alone.
  • ARIA only when no native element fits. The first rule of ARIA is not to use it when HTML already does the job; ARIA changes what assistive technology hears, not how an element behaves.
Which elements can the keyboard reach?

The span becomes reachable only because tabindex="0" was added, and it still would not react to Enter or Space without more code. That is the argument for native elements.

The box model

Q: Explain the CSS box model. Every element is a rectangular box made of four layers from inside out: content, padding, border and margin. With the default box-sizing: content-box, width and height set only the content, so padding and border are added on top. With box-sizing: border-box, width includes content, padding and border, which is why most projects reset it for everything:

CSS
*, *::before, *::after { box-sizing: border-box; }

Follow-ups to be ready for:

  • Margin collapsing: vertical margins of adjacent block siblings (and sometimes parent and first child) merge into the larger one instead of adding. Horizontal margins, flex items and grid items do not collapse.
  • Inline versus block: inline elements ignore width, height and vertical margins; inline-block accepts them.
  • Negative margins pull an element toward its neighbor; outline does not take up space, while border does.
content-box versus border-box

The first box renders 250px wide (200 content + 40 padding + 10 border); the second stays at 200px.

Specificity and the cascade

Q: How does the browser decide which CSS rule wins? The cascade compares, in order: importance (!important beats normal), origin (author styles beat the browser's defaults), specificity, and finally source order (the later rule wins a tie). Specificity is a three-part score:

Specificity, strongest first

IDs #main counts as 1-0-0.
Classes .card, [type], :hover count 0-1-0.
Elements p, ::before count 0-0-1.

Inline style attributes beat all selectors; !important beats those.

1 / 2

Counting is by column, not as one number: 0-1-0 always beats 0-0-9. The universal selector * and combinators add nothing. :is() takes the specificity of its most specific argument, :not() likewise, and :where() always counts as zero.

Which rule wins?

Flexbox versus grid

Q: When do you use flexbox and when grid? Flexbox lays items out along one axis (a row or a column), and the content decides sizes: good for navbars, toolbars, centering and distributing space. Grid controls two axes at once, and the layout decides where content goes: good for page layouts, galleries and anything where rows and columns must line up. They combine well: a grid for the page, flexbox inside each component.

One dimension or two?

Flexbox A row or a column at a time.
Grid Rows and columns together.

Content-first versus layout-first.

1 / 2

Notice what happens when the last row has fewer items than the others:

Flex wrap versus grid columns

Q: How do you center a div? Parent with display: grid; place-items: center;, or display: flex; justify-content: center; align-items: center;. For horizontal only, margin-inline: auto on a block with a set width.

Stacking contexts and z-index

Q: Why does z-index: 9999 sometimes not work? z-index only compares elements within the same stacking context. A stacking context is a self-contained layer group: everything inside it is stacked relative to its root, then the whole group is placed as one unit among its siblings. A child can never escape its parent's context, so a huge value inside a low context still loses to a sibling context with a higher value.

Things that create a stacking context: the root element; a positioned element with a z-index other than auto; a flex or grid item with a z-index other than auto; opacity below 1; transform, filter, perspective; isolation: isolate; will-change for those properties. isolation: isolate is the clean way to create one on purpose.

z-index 9999 trapped in a context

Advanced HTML5 questions: datalist, template, web components, dialog, contenteditable, microdata and geolocation

Once you have the semantic and accessibility basics, interviewers move to what modern HTML can do without a framework. These seven topics come up again and again. Remember that the previews on this site run in a sandbox, so features that need browser permissions (geolocation) are shown as read-only code.

What is <datalist>?

Short answer: <datalist> gives a text input a list of suggestions without taking away free typing. Link it with <input list="id">. It is not the same as <select>: a select restricts the user to the options, while a datalist only suggests, so you must still validate the final value on the server. It works with text-like types (text, search, url, email, number, range, color, date). Limits: styling of the suggestion popup is up to the browser, and screen-reader support varies, so always keep a visible <label>.

What is <template>, and what are web components?

<template> holds markup that the browser parses but does not render, run or load: images inside do not download and scripts do not run. You clone its content with JavaScript when you need it (template.content.cloneNode(true)). It is the native way to do client-side repeated markup.

Web components is the name for three browser standards that let you build your own reusable elements:

  • Custom elements: a JavaScript class that extends HTMLElement, registered with customElements.define("user-card", UserCard). The tag name must contain a hyphen. Lifecycle callbacks: connectedCallback (added to the page), disconnectedCallback, attributeChangedCallback (for attributes listed in static observedAttributes).
  • Shadow DOM: this.attachShadow({ mode: "open" }) creates an isolated subtree. Its CSS does not leak out and the page's CSS does not leak in (inherited properties and CSS custom properties still pass through, which is how you theme a component). <slot> lets the user supply content inside.
  • HTML templates: <template> (and <slot>) as above.
A custom element with a template and shadow DOM

The page rule h3 { color: crimson } does not touch the headings inside the cards, and the CSS variable --card-accent does pass in. That contrast is the usual "what does shadow DOM isolate?" answer.

<dialog> and the popover attribute

<dialog> is a native modal or non-modal window. dialog.show() opens it in place; dialog.showModal() opens it in the top layer with a backdrop (::backdrop), makes the rest of the page inert (no clicks, no focus), traps focus, closes on Esc, and returns focus to the opener when closed. dialog.close(returnValue) closes it, and a <form method="dialog"> button closes it automatically and sets returnValue to the button's value. Compared with a hand-built overlay of divs, you get the accessibility behavior for free. The popover attribute (with popovertarget on a button) is the lighter relative for menus and tooltips: light dismiss and top-layer placement without JavaScript.

contenteditable

contenteditable="true" makes any element editable: the browser supplies the caret, selection, undo and basic formatting. It is how rich-text editors start, and it is also why they are hard: browsers produce different HTML for the same edit, so serious editors (ProseMirror, Lexical, Tiptap) keep their own document model. Reading the result: use element.innerText or innerHTML, and sanitize any HTML you send back to a server (see the XSS notes above). contenteditable="plaintext-only" allows only plain text. spellcheck, inputmode and enterkeyhint are related attributes.

dialog and contenteditable working together

Microdata, structured data and itemprop

Microdata adds machine-readable meaning to visible HTML with attributes: itemscope (an item starts here), itemtype (a vocabulary URL, usually from schema.org) and itemprop (a property of the item). Search engines read it to build rich results (stars, prices, recipes). The other formats are RDFa and JSON-LD, and today JSON-LD (a <script type="application/ld+json"> block) is the one Google recommends, because it keeps the data separate from the layout. In an interview: say what it is for (SEO and machine readability, not styling), that none of it changes the rendering, and that you validate it with a rich-results tester.

Reading microdata back with the DOM

Geolocation

navigator.geolocation.getCurrentPosition(success, error, options) asks the browser for the device position. Key facts: it needs a secure context (HTTPS), it asks the user for permission (and may be denied or time out), accuracy ranges from meters (GPS) to kilometers (IP address), and watchPosition streams updates until you call clearWatch. Always handle the error callback (codes: permission denied, position unavailable, timeout) and feature-detect "geolocation" in navigator. It is not available in the sandboxed previews here, so the code below is read-only.

JavaScript
// Read-only: needs HTTPS and the user's permission
if (!("geolocation" in navigator)) {
  showManualCityInput();
} else {
  navigator.geolocation.getCurrentPosition(
    ({ coords }) => console.log(coords.latitude, coords.longitude, "ยฑ" + coords.accuracy + " m"),
    (error) => console.log(error.code === error.PERMISSION_DENIED ? "denied" : error.message),
    { enableHighAccuracy: false, timeout: 8000, maximumAge: 60000 }
  );
}

Privacy answer: ask only when the user triggers a feature that needs it, explain why, and offer a fallback such as typing a city.

Deeper CSS questions: positioning, custom properties, logical properties, transforms and animations

Specificity, the box model, flexbox versus grid and stacking contexts are covered above. These five topics fill the rest of a typical CSS round.

How do the position values differ?

Value Placed relative to In normal flow? Notes
static (default) Normal flow Yes top, left and z-index have no effect
relative Its own normal position Yes (its original space is kept) Offsets shift it visually; it becomes the containing block for absolute children
absolute The nearest positioned ancestor (any value except static), otherwise the initial containing block No (removed from flow) The parent may collapse because the child no longer takes space
fixed The viewport No Stays put on scroll; a transform or filter on an ancestor turns that ancestor into its containing block instead
sticky Its normal position until a scroll threshold, then it sticks inside its scroll container Yes Needs a top/bottom/left/right value; stops working if an ancestor has overflow: hidden/auto and no height to scroll against

The follow-up everyone asks: "my absolutely positioned child is in the wrong place". Look for the ancestor you expected to be positioned: it needs position: relative.

Which ancestor does an absolute element use?

What are CSS custom properties, and how are they different from Sass variables?

A custom property (--brand: #2563eb;) is read with var(--brand, fallback). Unlike a Sass variable, which is replaced at build time, a custom property lives in the browser: it cascades and inherits like any other property, can be overridden in a subtree or a media query, and can be changed at runtime from JavaScript (el.style.setProperty("--brand", "tomato")). That makes them the basis of themes (dark mode) and component APIs. Points to remember:

  • Declare global values on :root; override locally on a selector (.card { --pad: 8px }).
  • The second argument of var() is a fallback used when the property is not set. A property set to an invalid value for where it is used becomes "invalid at computed-value time" and falls back to inherit or initial, not to the fallback.
  • Names are case-sensitive and values are tokens, not types: --gap: 8 is not 8px. Use calc(var(--gap) * 1px) or register typed properties with @property (which also allows animating them).
  • They do not work in media query conditions, and they are not available in old browsers (IE).
Custom properties cascade, inherit and change at runtime

What are logical properties?

Physical properties name screen sides (margin-left, width, top). Logical properties name sides relative to the writing mode and direction: margin-inline-start, padding-block, inset-inline-end, inline-size, border-block-end, and the shorthands margin-inline, padding-block, inset. In a left-to-right language the inline axis is horizontal and start is the left; in an RTL language such as Arabic or Hebrew the same declarations flip automatically; in a vertical writing mode (writing-mode: vertical-rl) block and inline swap. They let one stylesheet serve every language, so mention them in any internationalization question. Also logical: text-align: start and float: inline-start.

The same CSS in left-to-right and right-to-left

How do transforms work, and what do they not do?

transform changes how an element is drawn without changing the layout: neighbors do not move, and the element's original box still takes its space. Functions: translate, rotate, scale, skew, and matrix, plus 3D versions (translateZ, rotateX, perspective). Rules to remember:

  • Order matters. transform: translate(100px) rotate(45deg) moves, then rotates; reversing them rotates the axes first, so the translation goes in a different direction. Transforms apply right to left in terms of coordinate systems.
  • transform-origin is the pivot (default 50% 50%).
  • Individual properties translate, rotate and scale exist and are easier to animate separately.
  • A transform (other than none) creates a stacking context and a containing block for fixed descendants.
  • Transforms do not affect inline non-replaced elements; they need display: block or similar.
  • They are GPU-friendly, which is why animations use them instead of left and top.

Transitions versus animations, and what is cheap to animate

A transition animates a property from its old to its new value when it changes (on hover, on a class change): transition: transform 200ms ease-out. It has only a start and an end. A @keyframes animation defines several steps, can run without a trigger, loop (animation-iteration-count: infinite), alternate and run with delays, and is controlled with animation-* properties.

Performance answer: the browser pipeline is style, layout, paint, composite. Animating width, height, top or margin triggers layout every frame; animating background-color triggers paint; animating transform and opacity usually needs only compositing on the GPU, which is why they stay smooth. will-change hints at an upcoming change but should be used sparingly because it reserves memory. Accessibility: respect users who ask for less motion with @media (prefers-reduced-motion: reduce).

Transform order, layout and a reduced-motion check

If an interviewer asks you to smoothly collapse a panel to height: auto, mention that height: auto cannot be transitioned directly. Options are to animate grid-template-rows from 0fr to 1fr, use interpolate-size: allow-keywords where supported, or animate max-height as a fallback.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A div has width: 200px; padding: 20px; border: 5px solid and the default box-sizing. How wide is the rendered box?

    With content-box, width sets only the content: 200 + 20 + 20 for padding + 5 + 5 for border = 250px. Under border-box it would be 200px.
  2. 2. Which selector has the highest specificity?

    #menu scores 1-0-0. The others score 0-3-0, 0-1-3 and 0-0-0: columns are compared left to right, so one id beats any number of classes.
  3. 3. Why is a native <button> better than a clickable <div>?

    Native elements bring behavior and accessibility semantics. Rebuilding them on a div needs tabindex, key handlers and ARIA.
  4. 4. A child has z-index: 9999 but is covered by a sibling of its parent that has z-index: 2. What is the most likely cause?

    z-index values are compared within one stacking context. The whole parent group is ordered as a unit among its siblings.
  5. 5. Which layout tool fits a page where rows and columns must line up, such as a photo gallery?

    Grid controls both axes at once, so tracks stay aligned. Flexbox is better for a single row or column of content.

Summary

  • Pick elements for meaning; native controls give keyboard support and roles, and ARIA is a last resort.
  • Accessibility basics: alt text, labels, heading order, visible focus, contrast, keyboard use.
  • box-sizing: border-box makes width include padding and border; vertical margins can collapse.
  • The cascade checks importance, origin, specificity (id-class-element columns), then order.
  • Flexbox is one-dimensional and content-driven, grid is two-dimensional and layout-driven.
  • z-index only works inside a stacking context; opacity, transform, filter and isolation create new ones.
  • <datalist> suggests, <template> holds inert markup, custom elements plus shadow DOM isolate styles, and <dialog> showModal() gives focus trapping and Esc for free.
  • contenteditable needs sanitizing; microdata and JSON-LD add machine-readable meaning; geolocation needs HTTPS, permission and an error handler.
  • Absolute positioning uses the nearest positioned ancestor; custom properties cascade and change at runtime, unlike Sass variables; logical properties follow writing direction.
  • Transforms change drawing but not layout and order matters; animate transform and opacity to avoid layout and paint, and honor prefers-reduced-motion.

Next: Browser, HTTP and Networking Questions.