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?
<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?
<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.
<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
<meta name="viewport" content="width=device-width, initial-scale=1" />
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?
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?
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?
<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
<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.
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?
<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?
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?
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?
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
<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?
<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?
<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
<!-- 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 & and raw characters?
<, >, 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 (<, >, &) represent those characters safely as text. Entities are also used for characters that are hard to type directly, like © for the copyright symbol.25. What is Cumulative Layout Shift, and what HTML causes it?
<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>?
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 |