Ad – 728Γ—90
🎯 Interview Prep

HTML Interview Questions – Top 40 Q&A for Beginners to Senior

Whether you are preparing for your first junior front-end role or a senior position, these 40 HTML interview questions cover the full spectrum β€” from "what is HTML?" to the critical rendering path and WCAG compliance. Each answer is concise enough to say in an interview, complete enough to actually understand.

⏱️ 35 min read🎯 BeginnerπŸ“… Updated 2026

Beginner Questions (1–15)

1. What is HTML?

HTML (HyperText Markup Language) is the standard language for creating web pages. It uses elements made up of tags (like <p>, <h1>, <a>) to describe the structure and meaning of content. Browsers parse HTML and render it as a visual page. HTML handles structure; CSS handles presentation; JavaScript handles behaviour.

2. What is the DOCTYPE declaration?

<!DOCTYPE html> is an instruction to the browser telling it which version of HTML the document uses. The modern HTML5 doctype is simply <!DOCTYPE html>. Without it, browsers switch to "quirks mode" β€” an old compatibility mode that mimics bugs from early browsers, causing inconsistent rendering. The doctype must be the very first line of every HTML file.

3. What is the difference between div and span?

<div> is a block-level container β€” it starts on a new line and takes up the full available width. <span> is an inline container β€” it sits within a line of text without breaking the flow. Both are generic containers with no semantic meaning; use semantic elements (<article>, <section>, <em>, etc.) when possible, and reach for div/span only for CSS/JS hooks.

4. What is semantic HTML?

Semantic HTML means choosing elements based on what the content means, not how it looks. For example, using <article> for a blog post, <nav> for navigation, <h1> for the page's main heading, and <strong> for important text β€” rather than styling divs and spans to look like headings. Semantic HTML improves accessibility (screen readers understand the structure), SEO (search engines understand content hierarchy), and code maintainability.

5. What is the difference between inline and block elements?

Block elements (<div>, <p>, <h1>–<h6>, <ul>, <table>) start on a new line and stretch to the full container width. Inline elements (<span>, <a>, <strong>, <img>, <input>) flow within a line of text and only take up as much width as their content. You can change this behaviour with CSS display property.

6. What are void elements (self-closing elements)?

Void elements are elements that cannot have children and therefore have no closing tag. Examples: <br>, <hr>, <img>, <input>, <meta>, <link>, <area>, <base>, <col>, <embed>, <source>, <track>, <wbr>. In HTML5, the trailing slash (<br />) is optional and has no effect β€” <br> is perfectly valid.

7. What is the difference between head and body?

The <head> element contains metadata about the page β€” the title, character encoding, CSS links, JavaScript links, meta tags for SEO and social sharing. This content is not displayed on the page. The <body> element contains all visible content β€” headings, paragraphs, images, links, forms. Everything the user sees is in <body>.

8. What does the alt attribute do on an img element?

The alt attribute provides a text alternative for an image. It serves three purposes: (1) Screen readers read it aloud for visually impaired users. (2) It displays as text if the image fails to load. (3) Search engines use it to understand the image content for indexing. Descriptive alt text is required for WCAG accessibility compliance. Use an empty alt="" for purely decorative images to tell screen readers to skip them.

9. What is the difference between id and class attributes?

An id must be unique on the page β€” only one element can have a given id. It is used for JavaScript targeting (getElementById), CSS styling of a single element, and in-page anchor links (href="#section-id"). A class can be applied to multiple elements and an element can have multiple classes. Classes are primarily used for CSS styling and JavaScript selection (getElementsByClassName, querySelectorAll).

10. What is the DOM?

The DOM (Document Object Model) is the browser's in-memory tree representation of an HTML document. When the browser parses HTML, it creates a tree of nodes β€” each element, attribute, and text becomes a node. JavaScript interacts with the page by reading and modifying this tree (document.getElementById(), element.textContent, element.appendChild(), etc.). Changes to the DOM update the visible page in real time.

11. What is the difference between strong and b?

Both render as bold text by default, but they have different semantic meanings. <strong> indicates that the text has strong importance β€” screen readers typically emphasise it with a different tone. <b> is purely presentational β€” it draws visual attention without implying importance (like a product name or a keyword in a review). Use <strong> for genuinely important content; use <b> when you want bold for stylistic reasons only.

12. How do you add a comment in HTML?

HTML comments use the syntax <!-- comment text -->. Comments are not rendered in the browser and are not read by screen readers, but they are visible in the page source. Never put sensitive information (passwords, API keys, internal notes) in HTML comments because anyone can view them.

13. What does charset="UTF-8" do?

The charset meta tag declares the character encoding of the HTML document. UTF-8 is a variable-width encoding that can represent every character in the Unicode standard β€” every language, emoji, and symbol. Without it, some browsers may default to a legacy encoding (like ISO-8859-1 for Western European), which causes characters from other languages to display as garbled symbols. The charset declaration must be the first element in <head>, within the first 1024 bytes of the file.

14. What are HTML entities?

HTML entities are character sequences that represent special characters which would otherwise be interpreted as HTML syntax. For example, &lt; renders as <, &gt; as >, &amp; as &, &quot; as ", &apos; as ', and &nbsp; as a non-breaking space. You must escape < and & in regular HTML text to prevent the browser misinterpreting them as tag starts or entity starts.

15. How do you link a CSS file to an HTML page?

Use the <link> element inside <head>: <link rel="stylesheet" href="style.css">. The rel="stylesheet" attribute tells the browser this is a CSS file. Always put <link> in <head> β€” placing it in <body> can cause a flash of unstyled content (FOUC) because the browser renders content before the styles arrive.

Ad – 336Γ—280

Intermediate Questions (16–30)

16. Describe the HTML5 new semantic elements.

HTML5 introduced structural semantic elements: <header> (introductory content/branding), <nav> (navigation links), <main> (primary content, unique per page), <article> (self-contained content like a blog post), <section> (themed group with a heading), <aside> (tangentially related content), and <footer> (closing content/credits). Smaller semantic elements include <figure>/<figcaption>, <time>, <mark>, <details>/<summary>, <progress>, and <meter>.

17. What is the difference between localStorage and sessionStorage?

Both are Web Storage APIs that store key-value strings in the browser. localStorage persists indefinitely β€” data survives browser restarts and tab closures until explicitly cleared. sessionStorage persists only for the current tab session β€” closing the tab clears the data. Both are scoped to the origin (protocol + domain + port). Neither is accessible via server-side code; use cookies for that. Neither is secure for sensitive data β€” always encrypt before storing.

18. How does a form GET request differ from POST?

A GET request appends form data to the URL as query parameters (/search?q=HTML&sort=date). It is bookmarkable, cacheable, and limited to URL length (~2000 chars). Use GET for non-destructive data retrieval (search, filters). A POST request sends data in the HTTP request body β€” not visible in the URL, not cached, no size limit. Use POST for creating/modifying data, file uploads, login forms, or anything with sensitive information.

19. What is the purpose of label for in forms?

The for attribute on a <label> element links it programmatically to the <input> whose id matches. This creates an accessible name for the input β€” screen readers read the label text when the input receives focus. It also makes the label click target activate the associated input, improving usability (especially for small checkboxes and radio buttons). An input without an associated label is inaccessible β€” it fails WCAG 1.3.1.

20. What are data- attributes?

Data attributes (data-*) allow you to store custom data on HTML elements without using non-standard attributes or adding invisible elements. For example: <button data-user-id="42" data-action="delete">. JavaScript accesses them via element.dataset.userId (note: kebab-case converts to camelCase). CSS can also read them with attribute selectors. They are useful for passing configuration from server-rendered HTML to JavaScript without making extra API calls.

21. Explain accessibility with ARIA.

ARIA (Accessible Rich Internet Applications) is a set of HTML attributes that supplement the native semantics of elements when those semantics are insufficient β€” primarily for custom interactive widgets. Key attributes: role overrides the element's implicit role; aria-label provides an accessible name when no visible text label exists; aria-describedby links to a description; aria-expanded communicates open/collapsed state; aria-hidden removes elements from the accessibility tree; aria-live announces dynamic content changes. Rule 1: always prefer native semantic HTML over ARIA.

22. What is the viewport meta tag?

The viewport meta tag tells mobile browsers how to scale the page: <meta name="viewport" content="width=device-width, initial-scale=1.0">. Without it, mobile browsers render the page at ~980px wide (their "virtual viewport") and then scale it down, making text tiny and requiring pinch-zoom. With width=device-width, the viewport matches the device's screen width, enabling responsive CSS to work correctly. initial-scale=1.0 prevents initial zoom. Never set user-scalable=no β€” it prevents users with visual impairments from zooming in and is a WCAG failure.

23. How does the srcset attribute work?

The srcset attribute on <img> allows you to provide multiple image versions for different screen densities and widths. The browser chooses the most appropriate one. Width descriptors (w): srcset="img-400.jpg 400w, img-800.jpg 800w" combined with sizes attribute tells the browser which image fits the layout. Density descriptors (x): srcset="img.jpg 1x, img@2x.jpg 2x" provides high-resolution versions for Retina screens. The src attribute serves as the fallback for older browsers.

24. What is the difference between article and section?

<article> represents a self-contained, independently distributable piece of content β€” it makes sense on its own, even without the surrounding page. Examples: blog posts, news articles, forum posts, product cards, comments. <section> represents a thematic grouping of content within a larger document. Sections are not self-contained β€” they are meaningful only in context. A rule of thumb: if you could copy the content and post it on a different site unchanged, it is an <article>. If it only makes sense in context, it is a <section>.

25. What is the canonical tag?

The canonical tag (<link rel="canonical" href="URL">) tells search engines which URL is the "official" version of a page when multiple URLs serve identical or very similar content. Common causes of duplicates: HTTP vs HTTPS, www vs non-www, trailing slashes, URL parameters, and pagination. Without canonicals, Google may split ranking signals across duplicates or index the wrong version. Best practice: add a self-referencing canonical to every page (pointing to itself), using the full absolute HTTPS URL.

26. What are Open Graph tags?

Open Graph (OG) tags are <meta property="og:*"> tags in <head> that control how your page appears when shared on social platforms (Facebook, LinkedIn, WhatsApp, Slack, Discord). The four required tags are og:title, og:type, og:url, and og:image. Adding og:description is strongly recommended. Use a 1200Γ—630px image for best results. Twitter/X uses similar tags prefixed with twitter:.

27. How do fieldset and legend help accessibility?

<fieldset> groups related form controls, and <legend> provides a caption for that group. Screen readers announce the legend text along with each input's label within the fieldset, giving context. For example, a group of radio buttons for "Payment method" β€” without the fieldset/legend, a screen reader user hears just "Visa β€” radio button" with no context about what they are choosing. With fieldset/legend they hear "Payment method β€” Visa β€” radio button".

28. What are boolean attributes?

Boolean attributes represent true/false states. In HTML, their mere presence makes them true β€” the value is irrelevant. Examples: disabled, checked, required, readonly, multiple, autoplay, muted, controls, hidden. All of these are equivalent: disabled, disabled="", disabled="disabled". To make the attribute false, remove it entirely β€” there is no disabled="false" in HTML (that would still be true).

29. What is the difference between relative and absolute URLs?

An absolute URL includes the full address: protocol, domain, path: https://ylearner.org/html/advanced/iframe.html. It works from any location. A relative URL is relative to the current page's location. ../canvas.html goes up one directory; ./canvas.html or canvas.html stays in the same directory; /html/advanced/canvas.html (root-relative) is relative to the site root. Use root-relative or absolute URLs for production links to avoid broken links when pages are moved.

30. How does lazy loading work for images?

The loading="lazy" attribute on <img> and <iframe> instructs the browser to defer loading the resource until it is near the user's viewport. This significantly reduces initial page load time β€” only images above the fold are loaded immediately; off-screen images load as the user scrolls. It is a native browser feature (no JavaScript needed), supported by all modern browsers. Always set loading="eager" (or omit the attribute) for above-the-fold images like hero images; never lazy-load the LCP (Largest Contentful Paint) image.

Advanced Questions (31–40)

31. What is the difference between progressive enhancement and graceful degradation?

Progressive enhancement starts with a minimal, universally supported baseline (semantic HTML, no JS) and layers on advanced features for capable browsers. The site works for everyone; better browsers get a richer experience. Graceful degradation starts with the full-featured modern version and ensures it still works (with reduced functionality) in older browsers. Progressive enhancement is generally preferred because it ensures accessibility and performance as a foundation rather than an afterthought.

32. Explain the critical rendering path.

The critical rendering path is the sequence of steps the browser takes to display the first pixel: (1) Parse HTML β†’ build DOM. (2) Download and parse CSS β†’ build CSSOM. (3) Combine DOM + CSSOM β†’ Render Tree (only visible nodes). (4) Layout (reflow) β€” calculate position and size of each node. (5) Paint β€” fill in pixels. (6) Composite β€” layer management for hardware acceleration. CSS and synchronous JavaScript in <head> are render-blocking β€” they pause HTML parsing. Optimising the CRP means reducing or deferring render-blocking resources.

33. What is Content Security Policy (CSP)?

Content Security Policy is an HTTP response header (or <meta http-equiv="Content-Security-Policy">) that tells browsers which sources are trusted for scripts, styles, images, frames, and other resources. It prevents XSS (Cross-Site Scripting) attacks by blocking inline scripts and scripts from untrusted origins. Example: Content-Security-Policy: default-src 'self'; script-src 'self' cdn.example.com; img-src * β€” this allows scripts only from the same origin and a specific CDN, and images from anywhere. A strict CSP with a nonce or hash is the most effective XSS defence.

34. How do iframes affect page performance?

Each iframe creates an independent browsing context with its own DOM, CSS engine, and JavaScript environment. The browser must parse and render the embedded document separately. Multiple iframes can block the main thread and delay the page's Largest Contentful Paint (LCP). Mitigations: use loading="lazy" to defer off-screen iframes; load iframes only on user interaction (e.g. replace a YouTube thumbnail with the iframe on click); avoid using iframes for content that can be inlined. Third-party iframes (ads, social widgets) are especially costly because their JavaScript may block the main thread.

35. What is the Shadow DOM?

The Shadow DOM is a browser API that creates an encapsulated sub-tree of DOM nodes attached to a regular DOM element, isolated from the main document's CSS and JavaScript. Styles defined inside a shadow root do not leak out, and external styles do not leak in. It is the technology that powers custom HTML elements like <video> (whose controls are actually a shadow DOM), and is the foundation of the Web Components standard along with Custom Elements and HTML Templates.

36. What are web components?

Web Components are a suite of native browser APIs that let you create reusable custom HTML elements: (1) Custom Elements β€” define new tags like <my-button> with custom behaviour using customElements.define(). (2) Shadow DOM β€” encapsulate the component's internal DOM and styles. (3) HTML Templates β€” define inert HTML fragments with <template> and <slot> for content projection. They work natively in all modern browsers without any framework.

37. How does the HTML parser handle errors?

Unlike XML, HTML parsers are fault-tolerant by specification. The HTML5 parsing algorithm defines exactly how to handle every type of malformed markup β€” unclosed tags, mismatched tags, attributes in wrong order. The browser attempts to create a sensible DOM rather than throwing an error. This is why pages with bad HTML often still render, but the DOM structure may differ from what you intended. Always validate your HTML with the W3C Validator to catch subtle errors that browsers silently "fix" in unexpected ways.

38. What is the difference between UTF-8 and UTF-16 in HTML?

UTF-8 and UTF-16 are both encoding schemes for Unicode characters. UTF-8 uses 1–4 bytes per character, is ASCII-compatible (the first 128 characters are identical to ASCII, each stored in 1 byte), and is the dominant encoding for the web. UTF-16 uses 2 or 4 bytes per character and is not ASCII-compatible. Always use UTF-8 for HTML documents (<meta charset="UTF-8">). Internally, browsers and JavaScript use UTF-16 β€” String.length in JavaScript counts UTF-16 code units, which is why emoji (which are 4-byte, 2 UTF-16 code units) have a length of 2.

39. Explain WCAG 2.1 levels A, AA, and AAA.

WCAG 2.1 (Web Content Accessibility Guidelines) has three conformance levels. Level A is the minimum baseline β€” failing these criteria makes the content inaccessible to some users (e.g. images need alt text, all functionality available by keyboard). Level AA is the standard legal target β€” required by most international accessibility laws (ADA, EAA, EN 301 549). Includes colour contrast 4.5:1, captions for video, reflow for 400% zoom. Level AAA is the highest level β€” not required by law for entire sites as it is not achievable for all content types. Includes 7:1 contrast ratio, sign language for all video.

40. What is the purpose of the preload attribute on link?

The <link rel="preload"> element tells the browser to fetch a resource at high priority during page load, even before it would normally discover it. This is critical for resources that appear late in the parsing order but are needed immediately: fonts, hero images, or JavaScript files loaded dynamically. Example: <link rel="preload" href="hero.jpg" as="image">. The as attribute is required β€” it tells the browser the resource type for correct caching and priority. Overusing preload wastes bandwidth; only preload your LCP resource and critical path fonts/scripts.

πŸ“‹ Summary

  • Beginner questions cover the fundamentals: DOCTYPE, block vs inline, semantic HTML, DOM, entities, and linking CSS.
  • Intermediate questions target the knowledge expected at junior-to-mid level: HTML5 elements, forms, ARIA, viewport, srcset, canonical, and lazy loading.
  • Advanced questions reflect senior expectations: critical rendering path, CSP, Shadow DOM, web components, parser error handling, and WCAG levels.
  • For every interview: relate answers to real accessibility, performance, and SEO impacts β€” not just definitions.

FAQ

How should I answer HTML questions in an interview?

Structure your answers with: the definition, the reason it matters (accessibility, performance, or SEO), and a concrete example. For example, instead of just saying "semantic HTML uses meaningful tags," add "which lets screen readers understand page structure, helps search engines rank content correctly, and makes the codebase easier to maintain."

What HTML topics should a junior developer know?

At minimum: all questions 1–15 in this guide plus form elements, the table structure, semantic elements (article/section/aside/header/footer/nav/main), alt text for images, and the difference between absolute and relative URLs. Understanding why each element exists β€” not just how to write it β€” sets strong junior candidates apart.

Is HTML enough for a front-end job?

HTML alone is not enough β€” you need CSS for styling and JavaScript for interactivity. However, deep HTML knowledge (semantics, accessibility, forms, SEO) is rarer than you would expect and is highly valued by employers. Many developers skip HTML fundamentals to jump to frameworks, then struggle with the basics in interviews. Solid HTML is a competitive advantage.