HTMLInterview Questions

HTML Interview Questions

Over 25 commonly asked HTML interview questions, with thorough answers covering semantics, accessibility, forms, SEO, performance, and browser behavior. Use this as a review guide before an interview, or as a way to test how deep your own understanding goes.

1. What is semantic HTML, and why does it matter?
Semantic HTML means choosing elements based on the meaning of the content, not just its visual appearance—using <nav> for navigation instead of a <div class="nav">, for example. It matters because semantics are what browsers, screen readers, and search engines use to understand structure: correct semantics give you free accessibility (landmarks, roles), better SEO signals, and more maintainable code, all without extra effort beyond picking the right tag.
2. What's the difference between block-level and inline elements?
Block-level elements (<div>, <p>, <section>) start on a new line, expand to fill their parent's width by default, and accept width/height. Inline elements (<span>, <a>, <strong>) flow within a line of text, only take up as much width as their content, and ignore top/bottom width/height/margin in most cases.
3. What are void (self-closing) elements? Give examples.
Void elements cannot have any children and never have a closing tag, because their content model is empty—there's nothing to put between an opening and closing tag. Examples: <img>, <br>, <hr>, <input>, <meta>, <link>. In HTML5 the trailing slash (<br />) is optional but commonly kept for readability and XHTML-style consistency.
4. What is the purpose of the doctype declaration?
<!DOCTYPE html> tells the browser to render the page in standards mode rather than the legacy "quirks mode" that emulates old, non-standard browser behavior. Without it, layout calculations (like box-sizing) can behave inconsistently across browsers. HTML5 simplified the doctype to this single, easy-to-remember line.
5. What does the meta viewport tag do, and why is it required for responsive design?

viewport.html

HTML
<meta name="viewport" content="width=device-width, initial-scale=1" />
Without it, mobile browsers render the page at a desktop-width virtual viewport (typically 980px) and then zoom out to fit the screen, making text tiny and defeating any responsive CSS. width=device-width tells the browser to match the viewport to the device's actual width, and initial-scale=1 sets the initial zoom level to 100%.
6. How does the browser validate a form natively, and how would you turn it off?
Attributes like required, pattern, min/max, and specialized type values (email, url) trigger built-in constraint validation when a form is submitted—the browser blocks submission and shows a native validation bubble if any constraint fails. Add novalidate to the <form> element to disable this and handle validation entirely in JavaScript instead.
7. Why is alt text important, and when should it be empty?
alt gives screen readers something to announce and gives users something to see if the image fails to load. It should describe the image's meaning in context, not restate that it's a picture. For purely decorative images that add no information (a background flourish, a spacer), use alt="" explicitly—an empty (but present) alt tells assistive technology to skip the image silently, whereas a missing alt attribute is announced awkwardly (often as the filename).
8. What is ARIA, and when should you use it?
ARIA (Accessible Rich Internet Applications) is a set of attributes— role, aria-label, aria-expanded, etc.—that describe roles, states, and properties to assistive technology, for cases native HTML can't express. The first rule of ARIA is to use it only when necessary: a native <button> already has the correct role, keyboard support, and focus behavior for free, so adding role="button" to a <div> only makes sense when no native element can do the job, and even then you must also replicate the keyboard behavior in JavaScript yourself.
9. What are the standard SEO meta tags every page should have?

Tag

Purpose

<title>

The clickable headline in search results

<meta name="description">

The snippet shown under the title in search results

<link rel="canonical">

Declares the authoritative URL when content is duplicated

<meta name="robots">

Controls whether/how the page is indexed and crawled

Open Graph tags (og:title, og:image)

Controls how the page looks when shared on social media

10. What's the difference between canvas and SVG?
<canvas> is a raster (pixel-based) drawing surface controlled entirely via JavaScript—once you draw a shape, the browser doesn't remember it as an object, only as pixels, so hit-testing and redraw logic is your responsibility. <svg> is vector-based and represented in the DOM as real, addressable elements—each shape is an individual node you can style with CSS, animate, and attach event listeners to directly. Canvas tends to scale better for a huge number of dynamic elements (particle effects, games); SVG tends to scale better for interactive, resolution-independent graphics (icons, charts, logos).
11. What are the web storage options in HTML5, and how do they differ?

Storage

Capacity

Persistence

Sent to server?

localStorage

~5–10MB

Persists until explicitly cleared

No

sessionStorage

~5–10MB

Cleared when the tab closes

No

Cookies

~4KB

Configurable expiry

Yes, on every matching request

IndexedDB

Large (browser-dependent, often 100MB+)

Persists until cleared

No

localStorage and sessionStorage share a simple synchronous key/value API (getItem/setItem) but only store strings. IndexedDB is asynchronous and supports structured data and larger datasets, at the cost of a more complex API.
12. What are the security risks of using iframes, and how do you mitigate them?
An unrestricted <iframe> can be used for clickjacking (overlaying an invisible iframe over fake UI to trick clicks) or to run untrusted scripts with full access to your page's context. Mitigations:
  • Use the sandbox attribute to restrict the capabilities of embedded content (scripts, forms, top-level navigation).

  • Set the Content-Security-Policy frame-ancestors directive (or the legacy X-Frame-Options header) to control who can embed your own pages.

  • Add loading="lazy" for iframes below the fold to limit unnecessary third-party code execution up front.

  • Only embed content from sources you trust, and prefer https origins.

sandboxed-iframe.html

HTML
<iframe
  src="https://widget.example.com/embed"
  sandbox="allow-scripts allow-same-origin"
  loading="lazy"
  title="Embedded widget"
></iframe>
13. Explain the difference between async and defer on a script tag.
Both download the script without blocking HTML parsing. The difference is execution timing: async executes the instant the download finishes (pausing the parser at that moment, in whatever order downloads complete), while defer waits until the document has finished parsing and then runs scripts in their original document order. Use defer for interdependent application code and async for independent scripts like analytics.
14. How does loading="lazy" improve performance, and when should you avoid it?
It defers downloading an <img> or <iframe> until the browser predicts the user is about to scroll it into view, reducing initial network/CPU load and improving metrics like Total Blocking Time. Avoid it on your Largest Contentful Paint candidate—typically a hero image above the fold—since the extra evaluation step before fetching actually delays that image's paint.
15. What's the difference between <script>, <script async>, and <script defer>, in terms of DOMContentLoaded?
A blocking script (no attribute) executes and completes before DOMContentLoaded can fire, since it must finish before the parser can finish building the DOM. defer scripts also always run before DOMContentLoaded, but without blocking parsing along the way. async scripts have no fixed relationship to DOMContentLoaded—they may execute before or after it fires, depending purely on download timing.
16. What is the Constraint Validation API?
It's the JavaScript API behind native HTML form validation—methods like checkValidity(), setCustomValidity(), and the validity property (with sub-properties like valueMissing, patternMismatch, tooShort) let you inspect and customize validation beyond what markup attributes alone provide, while still using the browser's native validation UI and events.
17. What is the difference between id and class attributes?
id must be unique per page and is used for a single, specific element—fragment links, label associations, JavaScript lookups by ID. class can be applied to any number of elements and is meant for grouping elements that share styling or behavior. A common mistake is using duplicate IDs where a shared class was actually intended.
18. What's the difference between localStorage and sessionStorage?
Both offer the same synchronous string-based key/value API, scoped to the page's origin. localStorage data persists across browser restarts until explicitly cleared; sessionStorage data is cleared automatically when the tab (not just the page) is closed, and isn't shared between tabs even on the same origin.
19. What are data-* attributes used for?

data-attributes.html

HTML
<button data-user-id="482" data-role="admin">Edit user</button>
data-* attributes let you attach custom data directly to HTML elements without inventing non-standard attributes or storing state separately. JavaScript reads them through the dataset property (e.g. button.dataset.userId), and they can also be targeted by CSS attribute selectors.
20. How do you make a custom clickable element (like a styled div) keyboard-accessible?
The honest answer is: don't—use a real <button> and style it, which gives you keyboard focus, Space/Enter activation, and the correct accessible role for free. If you're stuck with a non-native element, you'd need to add tabindex="0" to make it focusable, role="button" to announce its purpose, and JavaScript key handlers for Enter and Space—all of which a real button already does natively.
21. What is the critical rendering path?
It's the sequence of steps the browser performs before the first pixels appear: parsing HTML into the DOM, parsing CSS into the CSSOM, combining both into a render tree, computing layout (geometry), and finally painting pixels to the screen. Render- blocking resources—synchronous scripts and stylesheets in <head>—delay this pipeline and push first paint later.
22. What's the difference between <article> and <section>?
<article> marks content that makes sense on its own, independent of the rest of the page—a blog post, a news story, a product card—content you could syndicate elsewhere and it would still be complete. <section> marks a themed grouping of content within a larger document that typically needs a heading but doesn't need to stand alone. An <article> can contain <section> elements, and vice versa, depending on the content's structure.
23. Why should you avoid inline event handler attributes like onclick="..."?

inline-vs-listener.html

HTML
<!-- Avoid -->
<button onclick="deleteItem(3)">Delete</button>

<!-- Prefer -->
<button type="button" data-id="3" class="delete-btn">Delete</button>
<script>
  document.querySelectorAll('.delete-btn').forEach((btn) => {
    btn.addEventListener('click', () => deleteItem(btn.dataset.id));
  });
</script>

Inline handlers mix behavior into markup (harder to maintain, cache, and reuse), can be blocked by a strict Content-Security-Policy that disallows inline scripts, and don't support multiple listeners on the same event. Attaching listeners in JavaScript keeps concerns separated and works with CSP.

24. What's the difference between HTML entities like &amp; and raw characters?
Characters like <, >, and & have special meaning in HTML markup, so writing them literally in text content can be misparsed as the start of a tag or entity. Entities (&lt;, &gt;, &amp;) represent those characters safely as text. Entities are also used for characters that are hard to type directly, like &copy; for the copyright symbol.
25. What is Cumulative Layout Shift, and what HTML causes it?
Cumulative Layout Shift (CLS) is a Core Web Vital measuring how much visible content unexpectedly shifts position during a page's lifetime. The most common HTML-level cause is media without reserved dimensions—an <img> or <iframe> with no width/height (or CSS aspect-ratio) pushes surrounding content down the moment it finishes loading. Web fonts that swap in late, and dynamically injected banners/ads without a reserved slot, cause the same problem.
26. What's the difference between the defer attribute and placing a script at the end of <body>?
Both avoid blocking the initial render of visible content, but they differ in when the download starts. defer in <head> lets the browser discover and start downloading the script immediately, in parallel with parsing, while only delaying execution—so the script is often ready sooner. A script placed at the end of <body> with no attribute isn't even discovered until the parser reaches that point, so its download doesn't start until then, and it still blocks parsing (briefly, at the very end) while it executes.
27. How would you make a data table accessible to screen-reader users?
  • Use <th scope="col"> or scope="row" so each header’s association with its cells is explicit.

  • Add a <caption> describing the table’s purpose.

  • Avoid using tables purely for visual layout—reserve <table> for genuinely tabular data.

  • For complex tables with multi-level headers, use headers/id attribute pairs to associate specific cells with specific headers.

Quick Recap Table

Topic

One-line answer

Semantic HTML

Choosing elements for meaning, not just appearance

Block vs inline

Block starts a new line and fills width; inline flows with text

Void elements

Self-closing elements with no content model, e.g. <img>, <br>

Doctype

Triggers standards mode instead of quirks mode

Viewport meta tag

Required for correct mobile responsive scaling

alt text

Describes meaning; empty alt="" for decorative images

ARIA

Supplements native semantics; use only when no native element fits

canvas vs SVG

Canvas is pixel-based/imperative; SVG is vector-based/DOM elements

async vs defer

async executes on download-complete, unordered; defer executes in order after parsing

CLS

Unexpected layout shift; fix with reserved width/height on media

Explain the why, not just the what
Interviewers usually care more about why a practice exists (accessibility, performance, security) than reciting a definition. Ground each answer in the concrete problem the feature solves.
Practice explaining out loud
Reading answers is different from producing them under pressure. Try explaining each question above without looking, then check your answer against this page.