Complete HTML Interview Questions & Answer Bank
50 progressive HTML interview questions covering HTML5 semantics, accessibility (ARIA), web storage, media APIs, form validation, and web performance optimization.
Q1: What is the <!DOCTYPE html> declaration and why is it required?
The <!DOCTYPE html> declaration is an instruction to the web browser about the version of HTML used to render the document. It must be placed on the very first line of an HTML document. In HTML5, it triggers Standards Mode in modern browsers, preventing the browser from rendering the page in Quirks Mode or Limited Standards Mode, which emulate legacy browser behavior.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>The simple <!DOCTYPE html> declaration initiates HTML5 Standards Mode rendering without requiring legacy DTD references.
Enforces rendering in Standards Mode across all modern browsers.
Prevents legacy Quirks Mode rendering inconsistencies.
What happens if a web developer omits the <!DOCTYPE html> declaration?
Q2: What is Semantic HTML and why is it important?
Semantic HTML means using HTML tags according to their intended structural meaning rather than purely for presentation (e.g., using <header>, <nav>, <main>, <article>, <section>, and <footer> instead of generic <div> tags). Semantic HTML improves web accessibility (screen readers), SEO indexing, and code maintainability.
<header>
<nav>
<a href="/home">Home</a>
</nav>
</header>
<main>
<article>
<h2>Semantic Markup</h2>
<p>Semantic tags provide meaningful structure.</p>
</article>
</main>
<footer>
<p>© 2026 Web Standards</p>
</footer>Semantic landmarks establish structural hierarchies that allow screen readers to jump directly to primary page sections.
Describes meaning to browsers, search engines, and assistive technologies.
Improves SEO indexing and Screen Reader landmark navigation.
Which tag provides explicit main content landmark semantics to screen readers?
Q3: What is the difference between Block-level and Inline elements?
Block-level elements (e.g., <div>, <p>, <h1>, <ul>) start on a new line and expand horizontally to occupy the entire available width of their container. Inline elements (e.g., <span>, <a>, <strong>, <em>) flow inside textual content, taking up only as much width as required by their content, and do not respect vertical margins/padding.
<!-- Block Elements -->
<div>First Block</div>
<div>Second Block (Starts on new line)</div>
<!-- Inline Elements -->
<p>This is a <span style="color: red;">red inline tag</span> inside text.</p>Block elements break onto new lines and occupy 100% container width.
Inline elements stay in line with surrounding text and ignore top/bottom margins.
Which CSS properties are ignored by default on purely inline elements like <span>?
Q4: What is the difference between <script>, <script async>, and <script defer>?
Standard <script> blocks HTML parsing while fetching and executing JavaScript synchronously. <script async> fetches the script asynchronously in parallel with HTML parsing and executes it immediately as soon as downloading completes (blocking parsing briefly). <script defer> fetches asynchronously in parallel but postpones execution until HTML parsing is complete, maintaining script execution order.
<!-- Blocks DOM Parsing -->
<script src="app.js"></script>
<!-- Downloads in parallel, executes immediately on finish -->
<script async src="analytics.js"></script>
<!-- Downloads in parallel, executes after DOM parsing completes -->
<script defer src="main.js"></script>Using defer guarantees that DOM elements are fully constructed before script execution begins.
asyncexecutes immediately when downloaded, without guaranteeing execution order.deferexecutes in order after the HTML parser builds the DOM tree.
Which script attribute guarantees that multiple external scripts execute in their exact document order after parsing completes?
Q5: What is the difference between rel='preload' and rel='prefetch' in resource links?
rel="preload" informs the browser to fetch a critical resource (e.g., fonts, critical CSS, key JS bundles) as quickly as possible because it is needed for the current page view. rel="prefetch" asks the browser to fetch low-priority resources in the background during idle time because they might be needed for subsequent navigation pages.
<!-- Critical font needed for current page render -->
<link rel="preload" href="/fonts/custom.woff2" as="font" type="font/woff2" crossorigin>
<!-- Page bundle likely needed on next navigation step -->
<link rel="prefetch" href="/js/checkout-page.js">preload forces high priority loading for critical current view resources, while prefetch targets future routes.
preloadis high-priority for the current document rendering cycle.prefetchis low-priority for future navigation transitions.
Which resource link directive should be used for assets required on the next page a user is likely to visit?
Q6: What is the purpose of the <meta name='viewport'> tag in mobile responsive design?
The viewport meta tag instructs mobile web browsers how to control the page's dimensions and scaling behavior. Without this tag, mobile browsers render pages on a virtual desktop viewport (typically 980px wide) and scale the rendered output down, resulting in tiny text and broken mobile responsive CSS queries.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>width=device-width matches screen width in device-independent pixels, and initial-scale=1.0 establishes 1:1 zoom.
Sets view layout width to match the physical device screen width.
Prevents mobile browsers from simulating desktop viewport scaling defaults.
What occurs on mobile devices if the viewport meta tag is missing?
Q7: What is the difference between the src and href attributes in HTML?
src (Source) is used to embed or replace the current element with external resources (e.g., <img>, <script>, <iframe>). Loading a src resource halts parsing until it is fetched. href (Hypertext Reference) establishes a relationship between the current document and an external resource (e.g., <a href="...">, <link rel="stylesheet" href="...">).
<!-- href establishes relationship -->
<link rel="stylesheet" href="styles.css">
<a href="/about">About Us</a>
<!-- src embeds external content -->
<script src="app.js"></script>
<img src="logo.png" alt="Company Logo">href links to resources, whereas src replaces the element node with embedded external data.
srcembeds external resources directly into the document.hrefcreates links or associations pointing to external documents.
Which attribute is used to reference external images in an <img> tag?
Q8: How do the srcset and sizes attributes enable responsive images?
The srcset attribute defines a list of image sources along with width descriptors (e.g., 800w). The sizes attribute specifies media conditions and image display layout widths. Browsers use this information to select and download the optimal image asset resolution based on device display density and screen size.
<img src="small.jpg"
srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Responsive Landscape">The browser checks screen density and CSS layout rules to download the exact image resolution needed, saving mobile bandwidth.
srcsetlists candidate image files alongside width descriptors.sizesinforms the browser of the image layout width across media query breakpoints.
What descriptor is appended to image URLs inside the srcset attribute to declare asset pixel width?
Q9: When should you use the <picture> element instead of <img> with srcset?
Use the <picture> element for art direction (changing image cropping/aspect ratios for different viewports) or type fallback support (serving modern formats like WebP or AVIF with fallback to JPEG). Use <img> with srcset when you simply need the same image in different resolution sizes.
<picture>
<source srcset="hero.avif" type="image/avif">
<source srcset="hero.webp" type="image/webp">
<source media="(max-width: 600px)" srcset="hero-mobile.jpg">
<img src="hero-fallback.jpg" alt="Hero Banner">
</picture>The browser matches <source> elements top-to-bottom and picks the first supported format or media rule.
<picture>handles art direction cropping changes and format fallback negotiation.<img srcset>handles density/resolution switching for identical cropped images.
What primary requirement calls for the <picture> element over an <img> with srcset?
Q10: What is the sandbox attribute on <iframe> tags and why is it important?
The sandbox attribute applies strict security restrictions to content embedded inside an <iframe>. An empty sandbox attribute restricts the iframe from executing scripts, submitting forms, opening popups, reading cookies, or accessing same-origin resources. Developers selectively re-enable features using flags like allow-scripts or allow-forms.
<!-- Strict isolation: no scripts, no forms -->
<iframe src="https://example.com/widget" sandbox></iframe>
<!-- Permitted capabilities explicitly whitelist scripts -->
<iframe src="https://example.com/widget"
sandbox="allow-scripts allow-forms">
</iframe>The sandbox attribute prevents cross-site scripting (XSS) and frame-busting exploits from untrusted third-party embeds.
Restricts untrusted third-party iframe content from executing malicious actions.
Selective flags (
allow-scripts,allow-forms) grant explicit capabilities.
What happens when an <iframe> is specified with an empty sandbox attribute (<iframe sandbox>)?
Q12: What modern HTML5 <input> types exist and what benefits do they offer?
HTML5 introduced input types like email, url, tel, number, range, date, color, and search. These inputs provide native client-side validation, improve mobile accessibility by launching optimized virtual keyboards (e.g., numeric keypads for type="number" or email layout for type="email"), and provide built-in UI controls.
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<label for="age">Age:</label>
<input type="number" id="age" min="18" max="99">
<label for="dob">Birthdate:</label>
<input type="date" id="dob">
</form>Specialized input types prompt appropriate virtual keyboard modes on mobile devices and handle parsing validation.
Triggers mobile virtual keyboard adaptations (e.g.
@keys for email).Provides native browser input validation prior to form submission.
What is a primary usability benefit of using <input type='tel'> on mobile devices?
Q13: How do native HTML5 form validation attributes work?
HTML5 provides declarative validation attributes such as required, minlength, maxlength, min, max, step, and pattern (regular expressions). Browsers evaluate these constraints before triggering form submit actions and prevent form submission while displaying localized error popups if validation fails.
<form>
<!-- Must be 5 digits -->
<label for="zip">Zip Code:</label>
<input type="text" id="zip" pattern="[0-9]{5}" title="5 digit zip code" required>
<button type="submit">Submit</button>
</form>If the entered value fails the pattern regular expression, the browser halts form submission and shows validation feedback.
requiredenforces non-empty input fields.pattern="[A-Z]{3}"validates input against explicit Regular Expressions.
Which attribute on a <form> element completely turns off native browser validation checks?
Q14: What is the <datalist> tag and how does it complement <input>?
The <datalist> tag provides an autocomplete list of pre-defined options for an <input> element. Unlike a fixed <select> dropdown, <datalist> allows users to choose from suggested options or enter custom values freely.
<label for="browser">Choose a browser:</label>
<input list="browsers" id="browser" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
</datalist>The list="browsers" attribute links the input to the <datalist id="browsers"> suggestions container.
Connects to an
<input>via matchinglistattribute ID references.Combines flexible text input with suggested autocomplete options.
How does an <input> element bind to a <datalist> container?
Q15: What is ARIA (Accessible Rich Internet Applications) and when should it be used?
ARIA is a set of roles, states, and properties (role="...", aria-label="...", aria-expanded="...") defined by the W3C to make web content accessible to assistive technology. First Rule of ARIA: Use native semantic HTML elements (<button>, <nav>) whenever possible before applying ARIA attributes to generic elements.
<!-- Native button preferred -->
<button aria-expanded="false" aria-controls="menu-content">
Toggle Menu
</button>
<div id="menu-content" hidden>
<a href="/link">Link 1</a>
</div>aria-expanded and aria-controls communicate state changes to screen reader users.
Enhances accessibility when native semantic elements are insufficient.
First Rule of ARIA: Prefer native semantic tags over ARIA attributes on
<div>nodes.
What is the First Rule of ARIA according to W3C guidelines?
Q16: How do you associate a <label> with a form input correctly?
Explicit association uses the <label for="input-id"> matching the <input id="input-id">. Implicit association nests the <input> inside the <label> tag. Explicit association is widely preferred for robust assistive technology support.
<!-- Explicit Association (Recommended) -->
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<!-- Implicit Association -->
<label>
Password:
<input type="password" name="password">
</label>Clicking the associated <label> text focuses the corresponding form field automatically.
Explicit association matches
<label for="ID">with<input id="ID">.Increases click target size and announces input names to screen readers.
Which attribute on a <label> establishes explicit binding to an input's id?
Q17: What is the difference between <canvas> and <svg>?
<canvas>: Immediate-mode raster surface drawn procedurally via JavaScript. Resolution-dependent, highly performant for thousands of animated objects (games, data visualizations), but has no internal DOM node tree.<svg>: Retained-mode XML vector graphic format. Resolution-independent (scales crisply), supports CSS styling and event listeners on individual vector DOM shape nodes.
<!-- Canvas (Raster drawn via JS) -->
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const ctx = document.getElementById('myCanvas').getContext('2d');
ctx.fillRect(10, 10, 50, 50);
</script>
<!-- SVG (DOM Vector nodes) -->
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="red" />
</svg>SVG elements exist in the DOM and accept click handlers directly, whereas <canvas> renders pixels to a flat surface.
<canvas>is raster-based and drawn procedurally using JS canvas context APIs.<svg>is vector-based XML maintaining DOM shape nodes editable via CSS/JS.
Which graphics format is resolution-independent and represented as XML nodes in the DOM?
Q18: Why is <meta charset='UTF-8'> necessary in web documents?
The <meta charset="UTF-8"> tag specifies the character encoding of the HTML document. UTF-8 covers almost all human languages, symbols, and emojis. Placing this tag early inside <head> prevents character corruption, cross-site scripting (XSS) character encoding exploits, and unexpected symbol rendering.
<head>
<meta charset="UTF-8">
<title>Global Web Page</title>
</head>Declaring UTF-8 early ensures the browser parses subsequent textual characters correctly.
Guarantees correct character parsing across human languages and symbols.
Must be placed within the first 1024 bytes of the document inside
<head>.
Where should the <meta charset="UTF-8"> declaration be positioned in an HTML file?
Q20: What is the purpose of rel='noopener noreferrer' on external links?
When opening external links using target="_blank", the newly opened page gains access to the originating page's window.opener object, creating a security vulnerability (reverse tabnabbing). rel="noopener" prevents window.opener access. rel="noreferrer" also prevents sending the Referer HTTP header.
<!-- Secure external link -->
<a href="https://external.com" target="_blank" rel="noopener noreferrer">
Visit External Site
</a>rel="noopener" severs the connection between the new tab's window.opener property and the origin page.
Prevents reverse tabnabbing attacks on
target="_blank"links.Blocks third-party destination sites from manipulating
window.opener.
What security vulnerability is mitigated by adding rel="noopener" to target="_blank" links?
Q21: What is the contenteditable attribute in HTML?
The contenteditable attribute is an enumerated attribute that makes standard HTML elements (such as <div> or <p>) editable directly by users in the browser interface. It forms the foundation for Rich Text Editors (WYSIWYG editors) on the web.
<div contenteditable="true" style="border: 1px solid #ccc; padding: 10px;">
This text can be edited directly by the user in the browser.
</div>Setting contenteditable="true" allows users to edit inner HTML/text content directly.
Transforms standard DOM nodes into inline editable areas.
Can be controlled using JavaScript DOM selection APIs.
What primary feature is built using the contenteditable attribute?
Q22: What are custom data attributes (data-*) and how are they accessed in JavaScript?
Custom data attributes (data-*) allow embedding custom metadata directly on standard HTML elements without violating HTML specifications. In JavaScript, these values are accessed via the element's .dataset DOM property or using getAttribute(). In CSS, they are selected via attribute selectors [data-state='active'].
<button id="userBtn" data-user-id="9876" data-role="admin">User Profile</button>
<script>
const btn = document.getElementById('userBtn');
console.log(btn.dataset.userId); // Output: "9876"
console.log(btn.dataset.role); // Output: "admin"
</script>data-user-id converts to camelCase dataset.userId inside JavaScript.
Store arbitrary custom data formatted as
data-attribute-name.Read and write values in JavaScript via
element.dataset.attributeName.
How does the HTML attribute data-user-role map into JavaScript's dataset object?
Q24: What is Microdata and Structured Data (JSON-LD) in HTML?
Structured Data (Microdata attributes like itemscope, itemtype, or JSON-LD script blocks) provides machine-readable metadata about page entities (products, articles, recipes, events). Search engines use structured data to render Rich Snippets (star ratings, prices, event dates) in search results.
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Product",
"name": "Wireless Headphones",
"offers": {
"@type": "Offer",
"price": "99.99",
"priceCurrency": "USD"
}
}
</script>JSON-LD script blocks supply search engine crawlers with structured product data.
Annotates page content with standard Schema.org vocabulary schemas.
Enables Rich Search Engine Result Page (SERP) features.
What is the primary benefit of embedding JSON-LD structured data in an HTML document?
Q25: What is the Accessibility Tree and how does it relate to the DOM?
The Accessibility Tree is created by the browser based on the DOM tree. The browser translates DOM elements into accessibility nodes containing roles, names, states, and properties. Screen readers and assistive technologies consume the Accessibility Tree rather than inspecting the raw DOM directly.
<!-- DOM Node -->
<button aria-label="Close modal">X</button>
<!-- Accessibility Tree Mapping -->
<!-- Role: button | Name: "Close modal" | Action: click -->aria-label overrides the textual content 'X', presenting the accessible name 'Close modal' to screen readers.
Parallel data structure built by browsers alongside the DOM tree.
Consumed directly by screen readers to announce UI roles and states.
Which software technology consumes the Accessibility Tree to communicate web interfaces to visually impaired users?
Q26: How are <figure> and <figcaption> used together?
The <figure> element represents self-contained content (like diagrams, photos, code snippets, or illustrations), and <figcaption> supplies an optional caption or legend for its parent <figure> container.
<figure>
<img src="chart.png" alt="Quarterly Sales Chart">
<figcaption>Figure 1.1: Company quarterly revenue growth.</figcaption>
</figure>Semantic pairing binds the visual graphic directly to its explanatory caption text.
<figure>encapsulates independent illustrative media.<figcaption>must be placed as the first or last child inside<figure>.
Where must a <figcaption> tag be placed relative to its associated media?
Q28: What is the significance of the <title> tag for Web Accessibility and SEO?
The <title> tag defines the document name displayed in browser tab titles, bookmarks, and search engine results. It is the first element announced by screen readers when navigating to a new page, making accurate, unique titles critical for accessibility and search ranking.
<head>
<title>Shopping Cart | Acme Store</title>
</head>Descriptive titles help search engines categorize pages and give screen reader users immediate context.
Crucial for screen readers, search engines, and browser tab identification.
Should be unique and descriptive for every page in a web application.
Why is a unique <title> tag critical when users navigate a Single Page Application (SPA)?
Q29: What is the purpose of <meta name='robots'> directives?
The <meta name="robots"> tag controls search engine indexing and link-following behavior for individual pages. Common directives include index/noindex (whether to index the page) and follow/nofollow (whether to follow links on the page).
<head>
<!-- Prevent indexing and link following on admin pages -->
<meta name="robots" content="noindex, nofollow">
</head>Tells search engine spiders to skip indexing the document and avoid following page hyper-links.
noindexprevents search engines from indexing private or staging pages.nofollowtells crawlers not to follow links listed on the page.
Which meta robots directive prevents search engines from adding a page to search index results?
Q30: What are the advantages of using Inline <svg> over embedding SVG via <img src='...'>?
Inline SVG elements are injected directly into the HTML DOM. This allows developers to manipulate individual SVG vector shapes using CSS (fill, stroke, hover animations) and JavaScript event listeners. Embedded <img src="vector.svg"> images cannot be styled or targeted with CSS/JS internally.
<style>
.icon:hover { fill: #6366f1; }
</style>
<svg class="icon" width="24" height="24">
<circle cx="12" cy="12" r="10" />
</svg>Inline SVG paths and shapes accept direct CSS hover state fills and transitions.
Inline SVG enables direct CSS shape styling (
fill,stroke) and JS interactivity.Embedding via
<img>isolates the SVG into a separate un-styleable context.
What CSS capability is lost when rendering an SVG graphic using <img src="file.svg">?