HTML interview questions for freshers
Document structure, elements and attributes, lists, tables, links and entities, as asked in campus placements and first rounds.
What is HTML?
HTML (HyperText Markup Language) describes the structure and meaning of a web page. The browser parses it into the DOM; CSS styles it and JavaScript adds behavior.
Follow-up: is HTML a programming language? No, it has no variables, conditions or loops.
<h1>Orders</h1>
<p>You have <strong>3</strong> open orders. <a href="/orders">View them</a>.</p>
What is the difference between a tag, an element and an attribute in HTML?
A tag is the markup in angle brackets (<a>), an element is everything from the start tag to the end tag including the content, and an attribute is a name and value on the start tag (href="/docs"). After parsing, tags are gone: the DOM is a tree of elements.
What is <!DOCTYPE html> and why is it needed?
<!DOCTYPE html> tells the browser to render in standards mode. Without it, browsers fall back to quirks mode, which imitates old browser bugs, so the same CSS can lay out differently. It is a declaration, not a tag; the doctype page shows the old HTML 4 forms.
What is the basic structure of an HTML document?
A doctype, an <html> root, a <head> with metadata that is not displayed, and a <body> with the visible content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My first page</title>
</head>
<body>
<h1>Hello</h1>
<p>This text is inside the body, so it is visible.</p>
</body>
</html>Mention lang on <html>, <meta charset="utf-8"> early in the head, and the viewport tag, without which phones render the page at desktop width.
What is the difference between <head> and <header>?
<head> holds metadata (title, meta tags, stylesheets, scripts), is never displayed, and appears once. <header> is visible introductory content for the page or a section, such as a logo, title and navigation, and a page can have several.
What is the difference between block and inline elements?
A block element starts on a new line and takes the full width (<div>, <p>); an inline element flows inside text and is as wide as its content (<span>, <a>).
<!DOCTYPE html>
<style>
div, p { background: #dbeafe; }
span, a { background: #fde68a; }
span { width: 300px; height: 80px; } /* ignored: span is inline */
</style>
<div>A div takes the whole line.</div>
<p>A paragraph with <span>a span</span> and <a href="#">a link</a> that stay in the text.</p>The trap: width, height and vertical margins do not apply to inline text elements such as <span> and <a>. The CSS display property changes the type.
What is the difference between <div> and <span>?
Both are generic containers with no meaning: <div> is block-level and groups layout, <span> is inline and wraps text. Use them only when no semantic element such as <nav> or <button> fits, because those tell screen readers what the content is. More on the span page.
What are void (empty) elements in HTML?
Void elements cannot have content, so they have no end tag: <img>, <br>, <hr>, <input>, <meta>, <link>, <source> and a few others.
Follow-up: what about <br />? The slash is allowed and ignored. On other elements it means nothing: <div /> opens a div, and everything after it ends up inside.
What is the difference between id and class?
An id must be unique and identifies one element; a class can be shared by many elements, and an element can have several.
<!DOCTYPE html>
<style>
.tag { background: #e0e7ff; padding: 2px 8px; border-radius: 4px; }
#featured { outline: 2px solid #f59e0b; }
</style>
<p>
<span class="tag">html</span>
<span class="tag" id="featured">css</span>
<span class="tag">javascript</span>
</p>
<a href="#featured">Jump to #featured</a>Ids are targets for fragment links, <label for> and getElementById. Use classes for styling, since id selectors have higher specificity. See class selectors.
What are the new features in HTML5?
Semantic elements (<header>, <nav>, <main>, <article>), native <audio> and <video>, <canvas>, new input types with built-in validation, data-* attributes, APIs such as Web Storage and Web Workers, and the short doctype.
Follow-up: is there an HTML6? No. HTML is now a Living Standard, updated continuously.
What is the alt attribute on an image, and when should it be empty?
alt is the image's text alternative, read by screen readers, shown when the image fails to load, and used by search engines. Describe what the image shows or does in its context.
<img src="chart.png" alt="Sales grew from 40 to 65 orders a day in March">
<a href="/"><img src="logo.svg" alt="Coddy home"></a>
<img src="divider.png" alt="">
Use alt="" for decorative images. Leaving alt out is worse: some screen readers then read the file name.
What types of lists are there in HTML?
Three: <ul> for unordered items, <ol> for steps or rankings, and <dl> for term and description pairs.
<!DOCTYPE html>
<ul>
<li>Milk</li>
<li>Bread</li>
</ul>
<ol start="3">
<li>Third step</li>
<li>Fourth step</li>
</ol>
<dl>
<dt>HTML</dt>
<dd>Structure of the page</dd>
<dt>CSS</dt>
<dd>How it looks</dd>
</dl>Only <li> (plus <script> and <template>) may be a direct child of <ul> or <ol>, so a nested list goes inside an <li>. More on the lists page.
How do you create a table in HTML, and what do colspan and rowspan do?
A <table> holds rows (<tr>) of header cells (<th>) and data cells (<td>), optionally grouped in <thead> and <tbody>. colspan stretches a cell across columns, rowspan across rows.
<!DOCTYPE html>
<style>
table { border-collapse: collapse; }
th, td { border: 1px solid #94a3b8; padding: 4px 10px; }
</style>
<table>
<caption>Timetable</caption>
<thead>
<tr><th scope="col">Day</th><th scope="col">9:00</th><th scope="col">10:00</th></tr>
</thead>
<tbody>
<tr><th scope="row">Mon</th><td colspan="2">Lab (two hours)</td></tr>
<tr><th scope="row">Tue</th><td>Maths</td><td rowspan="2">Physics</td></tr>
<tr><th scope="row">Wed</th><td>English</td></tr>
</tbody>
</table>Use tables for data, never for layout. See colspan and rowspan.
What are HTML entities, and when do you need them?
Entities are codes for characters that would be read as markup or are hard to type, like <, &, or €.
<!DOCTYPE html>
<p>To start a paragraph, write <p>.</p>
<p>Tom & Jerry © 1940, price 10 €</p>On a UTF-8 page only <, & and quotes inside attribute values need escaping. Escaping user input this way is the basis of XSS prevention.
How do you open a link in a new tab, and why add rel="noopener"?
Add target="_blank", plus rel="noopener" so the new page cannot reach yours through window.opener.
<a href="https://example.com" target="_blank" rel="noopener noreferrer">Example</a>
Without it, the opened page could redirect your tab to a phishing page (reverse tabnabbing). Chrome 88, Firefox 79 and Safari 12.1 and later apply noopener to target="_blank" by default (see MDN on noopener), but writing it is still expected. See opening links in a new tab.
How do you write a comment in HTML, and are comments visible to users?
Write <!-- text -->. Comments are not rendered but are sent with the page, so anyone can read them in View Source; never put keys or internal notes there. They cannot be nested: the first --> ends the comment.
What are the ways to add CSS to an HTML page?
Three: an inline style attribute, an internal <style> element, and an external stylesheet linked with <link rel="stylesheet">.
<head>
<link rel="stylesheet" href="styles.css"> <!-- external -->
<style>p { line-height: 1.6; }</style> <!-- internal -->
</head>
<body>
<p style="color: crimson;">Inline</p> <!-- inline -->
</body>
Use external stylesheets on real sites, since the browser caches them. Inline styles beat stylesheet rules unless a rule uses !important. See external CSS.
Is HTML case-sensitive?
Tag and attribute names are not; the parser lowercases them. Many attribute values are: id="Main" and id="main" are different ids, and class names are compared exactly (quirks mode makes CSS class and id matching case-insensitive). Write everything lowercase.
What is the difference between HTML and XHTML?
XHTML is HTML in XML syntax, read by a parser that stops at the first error; the HTML parser repairs mistakes. Only a page served as application/xhtml+xml gets the XML parser, so text/html is HTML however it is written.
| HTML | XHTML | |
|---|---|---|
| Names | Case-insensitive | Lowercase only |
| Void elements | <br> | <br /> |
| End tags | Some optional | Always required |
What are boolean attributes, and what does disabled="false" do?
A boolean attribute is true when present and false when absent, whatever its value. So disabled="false" still disables the element.
<button disabled>Disabled</button>
<button disabled="false">Still disabled</button>
<button>Enabled</button>
To turn one off, remove the attribute (removeAttribute("disabled")) or set the property button.disabled = false. Others: checked, required, readonly, multiple, open.
Semantic HTML interview questions
Choosing elements by meaning: article vs section, strong vs b, headings, main and the HTML5 elements.
What is semantic HTML, and why does it matter?
Semantic HTML means choosing elements for what the content is, not how it looks: <nav> for navigation, <button> for a button, instead of divs everywhere.
<!DOCTYPE html>
<style>
body { font-family: system-ui, sans-serif; }
header, nav, main, aside, footer { border: 1px dashed #94a3b8; margin: 4px 0; padding: 4px 8px; }
</style>
<header>Site name
<nav><a href="#">Home</a> <a href="#">Courses</a></nav>
</header>
<main>
<article>
<h1>Learning HTML</h1>
<p>An article with its own heading.</p>
</article>
<aside>Related links</aside>
</main>
<footer>Contact and copyright</footer>Screen readers expose these as landmarks to jump between, and native elements bring behavior, such as keyboard support on <button>. See semantic HTML.
What is the difference between <article> and <section>?
<article> is self-contained content that makes sense alone: a blog post, a comment, a product card. <section> is a thematic part of something larger, normally with a heading. The test: could you publish it alone, in a feed?
<article>
<h1>How to center a div</h1>
<section><h2>With flexbox</h2>...</section>
<section><h2>With grid</h2>...</section>
</article>
They nest both ways; a wrapper for styling only is a <div>.
When should you use <section> instead of <div>?
Use <section> for a distinct part of the document with its own heading, and <div> for a styling or layout wrapper.
<section aria-labelledby="pricing-title">
<h2 id="pricing-title">Pricing</h2>
<div class="cards">...</div> <!-- layout wrapper only -->
</section>
A <section> with no heading usually should have been a <div>. A section with an accessible name becomes a region landmark, so do not name every one.
What is the difference between <b> and <strong>, and between <i> and <em>?
<strong> marks importance (a warning) and <em> marks stress emphasis that changes a sentence's meaning. <b> and <i> set text apart without adding importance: a keyword, a product name, a foreign term.
<!DOCTYPE html>
<p><strong>Warning:</strong> this deletes your account.</p>
<p>I <em>did</em> send the email. (stress changes the meaning)</p>
<p>The <b>Pro plan</b> includes the <i lang="fr">je ne sais quoi</i> you wanted.</p>They look the same by default. For bold text that is only design, use CSS font-weight.
What is the <main> element, and what are its rules?
<main> wraps the content unique to this page, not the header, navigation, sidebar or footer. Screen readers expose it as the main landmark, and skip links point at it. A document has one visible <main>, and it never goes inside <article>, <section>, <aside>, <header>, <footer> or <nav>.
Can a page have more than one <h1>?
Yes, it is valid, but the usual advice is one <h1> naming the page, then <h2> to <h6> in order. The section-based outline algorithm that would have demoted an <h1> inside a <section> was never implemented, and in 2022 the spec replaced it with an outline built from heading levels, so an <h1> in a <section> is still announced as level 1.
What are <figure> and <figcaption> used for?
<figure> wraps self-contained content the text refers to (an image, chart, code listing or quote), and <figcaption> captions it as the first or last child.
<!DOCTYPE html>
<figure>
<svg width="160" height="90" role="img" aria-label="Bar chart">
<rect x="10" y="50" width="30" height="40" fill="#60a5fa"/>
<rect x="60" y="25" width="30" height="65" fill="#3b82f6"/>
<rect x="110" y="5" width="30" height="85" fill="#1d4ed8"/>
</svg>
<figcaption>Figure 1: Signups per quarter.</figcaption>
</figure>The caption does not replace alt on an image inside it: alt describes the image, the caption comments on it.
How do you make an accordion without JavaScript?
Use <details> and <summary>: the summary stays visible and toggles the rest, with keyboard and screen reader support built in.
<!DOCTYPE html>
<style>
details { border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px 10px; margin: 6px 0; }
summary { cursor: pointer; font-weight: 600; }
</style>
<details name="faq" open>
<summary>Is the course free?</summary>
<p>The first lessons are free.</p>
</details>
<details name="faq">
<summary>Do I need to install anything?</summary>
<p>No, the code runs in the browser.</p>
</details>open shows it expanded. In current browsers, several <details> sharing a name are exclusive: opening one closes the others. More on the details page.
What is the <time> element for?
<time> marks a date, time or duration, with a machine-readable value in datetime while the visible text stays human-friendly.
<p>Published <time datetime="2026-03-14">14 March 2026</time></p>
<p>Reading time: <time datetime="PT7M">7 minutes</time></p>
Search engines and calendar tools read the exact value. Without datetime, the text itself must be in a valid machine format.
HTML forms and inputs interview questions
How forms send data, input types, labels, validation and the attributes behind common form bugs.
How does an HTML form send data, and why does every input need a name?
On submit, the browser sends name=value pairs for every enabled field that has a name, to the action URL with the method. A field without a name is not sent.
<!DOCTYPE html>
<form action="/signup" method="post">
<label>Email <input type="email" name="email" value="asha@example.com"></label>
<label>Nickname <input type="text" value="no name, not sent"></label>
<button>Sign up</button>
</form>Press the button: only email is sent. Defaults: method is get and action is the current URL. See the form page.
What is the difference between GET and POST in a form?
GET puts form data in the URL; POST puts it in the request body. Use GET for searches and filters that only read, POST for anything that changes data or sends private or large data.
The trap: POST is not more secure, only HTTPS encrypts. HTML forms support only get, post and dialog.
Why should you use <label> with form inputs?
A <label> gives an input its accessible name, so screen readers announce it, and clicking the label focuses or toggles the input.
<!DOCTYPE html>
<p>
<input type="checkbox" id="terms">
<label for="terms">I accept the terms (click this text)</label>
</p>
<p>
<input type="checkbox"> No label: only the tiny box is clickable
</p>
<label>Wrapped label <input type="text" name="city"></label>Connect them with for and the input's id, or by nesting the input inside the label. A placeholder does not replace a label. See the label page.
What input types does HTML5 provide?
HTML5 added email, url, tel, number, range, date, time, color, search and a few more date types.
<!DOCTYPE html>
<style>label { display: block; margin: 6px 0; }</style>
<label>Email <input type="email"></label>
<label>Phone <input type="tel"></label>
<label>Quantity <input type="number" min="1" max="10" value="2"></label>
<label>Volume <input type="range" min="0" max="100"></label>
<label>Date <input type="date"></label>
<label>Color <input type="color" value="#2563eb"></label>They bring the right control, built-in validation and the right phone keyboard; an unknown type falls back to text. Use tel, not number, for phone numbers. All types are on the input types page.
What is the difference between radio buttons and checkboxes?
Radio buttons pick exactly one option from a group; checkboxes are independent. Radios form a group by sharing the same name.
<fieldset>
<legend>Plan</legend>
<label><input type="radio" name="plan" value="free" checked> Free</label>
<label><input type="radio" name="plan" value="pro"> Pro</label>
</fieldset>
<label><input type="checkbox" name="newsletter" value="yes"> Send me news</label>
An unchecked checkbox sends nothing, and a checked one without a value sends on. Radios with different names are separate groups. See the radio button page.
How does built-in form validation work in HTML5?
Attributes like required, type="email", pattern, min, max and minlength make the browser check fields on submit and block it with a message, without JavaScript.
<!DOCTYPE html>
<style>input:user-invalid { outline: 2px solid crimson; }</style>
<form>
<label>PIN code
<input name="pin" required pattern="[0-9]{6}" title="Six digits">
</label>
<label>Age <input name="age" type="number" min="18" max="99"></label>
<button>Save</button>
</form>pattern must match the whole value, and setCustomValidity() adds custom rules. The server must validate again, since anyone can bypass the browser.
What is the difference between readonly and disabled?
A readonly field cannot be edited but is focusable and is submitted. A disabled field cannot be focused and is not submitted.
<!DOCTYPE html>
<form>
<label>Order id <input name="order" value="A-1042" readonly></label>
<label>Coupon <input name="coupon" value="SAVE10" disabled></label>
<button>Submit</button>
</form>Submit and only order is sent, the classic bug when a field is disabled to stop editing. readonly has no effect on checkboxes, radios or <select>.
What is the default type of a <button> inside a form?
What is the difference between <select> and <datalist>?
A <select> restricts the user to its options. A <datalist> only suggests values for a text input; the user can type anything.
<!DOCTYPE html>
<label>Course
<select name="course">
<option value="html">HTML</option>
<option value="css" selected>CSS</option>
</select>
</label>
<label>City
<input name="city" list="cities" placeholder="Type or pick">
</label>
<datalist id="cities">
<option value="Bengaluru"></option>
<option value="Hyderabad"></option>
<option value="Pune"></option>
</datalist>Use <select> when only listed values are valid and <datalist> for autocomplete with free input.
What do you need in a form to upload a file?
An <input type="file"> and, on the form, method="post" with enctype="multipart/form-data". With the default encoding only the file name is sent, not its contents.
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="resume" accept=".pdf,application/pdf">
<input type="file" name="photos" accept="image/*" multiple>
<button>Upload</button>
</form>
accept only filters the file picker, so the server must still check type and size.
What does the autocomplete attribute do, and why is autocomplete="off" often ignored?
autocomplete tells the browser what a field holds (email, tel, postal-code, current-password, new-password, one-time-code) so autofill and password managers fill it correctly.
<input name="email" type="email" autocomplete="email">
<input name="password" type="password" autocomplete="current-password">
<input name="otp" inputmode="numeric" autocomplete="one-time-code">
Browsers may ignore autocomplete="off" on login fields on purpose, because blocking password managers pushes users toward weak passwords.
HTML5 APIs and media interview questions
Audio, video, canvas and SVG, data attributes, dialog, template and the browser APIs that came with HTML5.
How do you add audio and video to a page?
With <audio> and <video>. Add controls for the browser's player, list <source> elements in several formats (the first supported one plays), and put fallback text inside.
<video controls width="640" height="360" poster="cover.jpg">
<source src="intro.webm" type="video/webm">
<source src="intro.mp4" type="video/mp4">
<track kind="captions" src="intro.en.vtt" srclang="en" label="English">
Your browser does not support video. <a href="intro.mp4">Download it</a>.
</video>
poster shows an image before playback, and <track> adds WebVTT captions. See the video page.
Why does autoplay not work on my video?
Browsers block autoplay with sound, so a video with autoplay usually plays only when it is also muted.
<video autoplay muted loop playsinline src="hero.mp4"></video>
playsinline asks mobile browsers to play it in the page, not full screen. video.play() returns a promise that rejects when autoplay is blocked; catch it and show a play button.
What is the difference between <canvas> and SVG?
SVG is vector graphics made of DOM elements; <canvas> is a bitmap you draw on with JavaScript, with no record of the shapes.
<!DOCTYPE html>
<svg width="120" height="120">
<circle cx="60" cy="60" r="40" fill="#3b82f6"><title>SVG circle</title></circle>
</svg>
<canvas id="c" width="120" height="120"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.fillStyle = '#f59e0b';
ctx.beginPath();
ctx.arc(60, 60, 40, 0, Math.PI * 2);
ctx.fill();
</script>SVG stays sharp when scaled, and each shape can be styled, clicked and read by screen readers, but thousands of nodes get slow. Canvas suits games and charts with very many points.
What is the difference between localStorage, sessionStorage and cookies?
localStorage persists until cleared and is shared by the origin's tabs; sessionStorage lives in one tab until it closes; cookies (about 4 KB each) go to the server with every request. Any script on the page can read storage but not an HttpOnly cookie, so session tokens belong in one.
What are data-* attributes, and how do you read them?
data-* attributes store custom values on an element. JavaScript reads them through element.dataset (data-user-id becomes dataset.userId), and CSS can select on them.
<!DOCTYPE html>
<style>
button[data-active="true"] { outline: 3px solid #f59e0b; }
</style>
<button data-color="#bfdbfe" data-label="Blue">Blue</button>
<button data-color="#bbf7d0" data-label="Green">Green</button>
<p id="out">Pick a color</p>
<script>
document.querySelectorAll('button').forEach((b) => {
b.addEventListener('click', () => {
document.querySelectorAll('button').forEach((x) => (x.dataset.active = 'false'));
b.dataset.active = 'true';
document.body.style.background = b.dataset.color;
document.getElementById('out').textContent = 'Picked ' + b.dataset.label;
});
});
</script>Values are always strings, and they sit in the page source, so never put secrets there.
How does the <dialog> element work?
<dialog> is a native modal. showModal() opens it above a page made inert, closes it on Escape and styles the overlay with ::backdrop; close(value) sets returnValue.
<!DOCTYPE html>
<style>dialog::backdrop { background: rgb(0 0 0 / 0.4); }</style>
<button id="open">Delete file</button>
<p id="result"></p>
<dialog id="confirm">
<p>Delete this file?</p>
<button id="yes">Delete</button>
<button id="no">Cancel</button>
</dialog>
<script>
const d = document.getElementById('confirm');
document.getElementById('open').onclick = () => d.showModal();
document.getElementById('yes').onclick = () => d.close('delete');
document.getElementById('no').onclick = () => d.close('cancel');
d.addEventListener('close', () => {
document.getElementById('result').textContent = 'returnValue: ' + d.returnValue;
});
</script>A <form method="dialog"> inside it closes it on submit, with the button's value as returnValue.
What is the <template> element?
<template> holds HTML that is parsed but not rendered: its images do not load and its scripts do not run until you clone the content into the page.
<!DOCTYPE html>
<template id="row">
<li><strong class="name"></strong>: <span class="score"></span></li>
</template>
<ul id="list"></ul>
<script>
const players = [['Asha', 42], ['Ravi', 37], ['Meera', 51]];
const tpl = document.getElementById('row');
for (const [name, score] of players) {
const li = tpl.content.cloneNode(true);
li.querySelector('.name').textContent = name;
li.querySelector('.score').textContent = score;
document.getElementById('list').append(li);
}
</script>template.content is a DocumentFragment. Filling clones with textContent means user data is never parsed as markup.
What are Web Workers, and what can they not do?
A Web Worker runs JavaScript on a background thread so long computations do not freeze the page. It cannot touch the DOM; it talks to the page with messages.
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ numbers: bigArray });
worker.onmessage = (e) => console.log('sum', e.data);
// worker.js
onmessage = (e) => {
const sum = e.data.numbers.reduce((a, b) => a + b, 0);
postMessage(sum);
};
Follow-up: what is a service worker? A worker that sits between the page and the network, for offline caching and push notifications.
How does the Geolocation API work?
navigator.geolocation.getCurrentPosition() asks the user for permission and, if granted, passes latitude, longitude and accuracy to a callback. It works only on secure pages (HTTPS or localhost).
navigator.geolocation.getCurrentPosition(
(pos) => console.log(pos.coords.latitude, pos.coords.longitude, pos.coords.accuracy),
(err) => console.log('No location:', err.message),
{ enableHighAccuracy: false, timeout: 10000 }
);
Handle the error callback, since users can refuse, and ask after a user action, not on page load.
HTML accessibility interview questions
Labels, ARIA, keyboard support, focus and live regions, now standard in front end interviews.
What is web accessibility, and how does HTML help?
Web accessibility (a11y) means people with disabilities can use the site, whether they use a screen reader, only a keyboard, or have low vision. Most of it is correct HTML: semantic elements, alt text, labels on inputs, lang on <html>, and keyboard access with visible focus. The standard is WCAG.
Why should you set the lang attribute on <html>?
lang tells browsers and assistive technology the page's language, so screen readers pick the right pronunciation and browsers offer translation.
<html lang="en">
...
<p>The Hindi word <span lang="hi">नमस्ते</span> means hello.</p>
Without it, an English screen reader may read a Hindi page with English pronunciation. Values are language codes with an optional region: en, hi, en-IN. See the lang attribute page.
What is ARIA, and when should you use it?
ARIA attributes (role, aria-label, aria-expanded, aria-live) tell assistive technology what a custom widget is and what state it is in. Use them only when no native element does the job.
<!-- Good: native button, no ARIA needed -->
<button>Save</button>
<!-- ARIA describes state that HTML cannot express -->
<button aria-expanded="false" aria-controls="menu">Menu</button>
The trap: ARIA changes what is announced, never behavior. role="button" does not make a div focusable or usable from the keyboard.
Why is <div onclick> not a good replacement for <button>?
What is the difference between aria-label, aria-labelledby and aria-describedby?
aria-label names an element with a string, aria-labelledby takes the name from other elements by id, and aria-describedby adds a description read after the name.
<button aria-label="Close dialog">×</button>
<h2 id="billing">Billing address</h2>
<section aria-labelledby="billing">...</section>
<input id="pw" type="password" aria-describedby="pw-hint">
<p id="pw-hint">At least 12 characters.</p>
aria-labelledby beats aria-label, which beats the native label. Put hints and errors in aria-describedby so they are heard on focus.
What do tabindex="0", tabindex="-1" and a positive tabindex do?
tabindex="0" adds an element to the Tab order at its document position. tabindex="-1" makes it focusable from script (el.focus()) but not with Tab, which suits a heading you move focus to. A positive value jumps ahead of everything else.
<div role="button" tabindex="0">Custom control</div>
<h2 id="results" tabindex="-1">Results</h2> <!-- focused by script after a search -->
Avoid positive values: the Tab order stops following the visual order.
What is a skip link, and how do you build one?
A skip link is the first link on the page and jumps to the main content, so keyboard users skip the header and menu. It is hidden until focused.
<!DOCTYPE html>
<style>
.skip { position: absolute; left: -9999px; }
.skip:focus { left: 8px; top: 8px; background: #fde68a; padding: 6px 10px; }
nav { height: 220px; background: #f1f5f9; }
</style>
<a class="skip" href="#main">Skip to main content</a>
<nav>Logo, menu, search, account links...</nav>
<main id="main" tabindex="-1">
<h1>Main content</h1>
</main>Click in the preview and press Shift+Tab to see it. Hide it off screen, not with display: none, which takes it out of the Tab order.
How do you announce dynamic changes to screen reader users?
Put the changing text in a live region: aria-live="polite" waits for a pause, aria-live="assertive" interrupts. role="status" and role="alert" are the same two.
<!DOCTYPE html>
<button id="save">Save</button>
<p role="status" id="status"></p>
<script>
document.getElementById('save').onclick = () => {
document.getElementById('status').textContent = 'Saved at ' + new Date().toLocaleTimeString();
};
</script>The trap: the region must be in the DOM before its text changes; an element inserted with the message already inside is often not announced.
How do you test a page for accessibility?
Combine automated checks with manual testing, because tools catch only part of the problems.
- Automated: Lighthouse or axe, also in CI.
- Keyboard: every control reachable with Tab, focus visible, no trap.
- Screen reader: NVDA, VoiceOver or TalkBack.
- Zoom and contrast: 200% zoom, text contrast at least 4.5:1, or 3:1 for large text (WCAG AA).
HTML SEO and meta tags interview questions
Title, description, viewport, charset, canonical, Open Graph, robots, hreflang and structured data.
Which HTML tags matter most for SEO?
What does the viewport meta tag do?
<meta name="viewport" content="width=device-width, initial-scale=1"> tells mobile browsers to lay the page out at the screen's width. Without it, phones use a desktop width (often 980px) and zoom out, so text is tiny and media queries misfire.
Do not add maximum-scale=1 or user-scalable=no: blocking pinch zoom stops low vision users from enlarging text, which WCAG resize text asks to work up to 200%. See the viewport page.
Do the meta description and meta keywords tags affect ranking?
Not directly. Google ignores <meta name="keywords">, and the description is not a ranking factor, but it is often shown as the snippet under your title, so a good one earns clicks.
<title>Learn HTML Forms with Examples</title>
<meta name="description" content="Build forms with labels, input types and validation. Every example runs in the browser.">
Write a unique description for each page; Google may shorten or rewrite it. The <title> does affect ranking.
Why do you need <meta charset="utf-8">, and where does it go?
It tells the browser how to decode the page's bytes into characters; with the wrong encoding Café shows up as Café. The spec requires it within the first 1024 bytes, so put it first in <head>. A Content-Type HTTP header with a charset takes priority over it, so the two should agree.
What is a canonical link, and when do you need one?
<link rel="canonical" href="..."> names the preferred URL when the same content is reachable at several URLs, so ranking signals are combined on one page.
<link rel="canonical" href="https://example.com/shoes/running">
Duplicates usually come from tracking and filter parameters. Use an absolute URL. Google treats it as a hint and can pick another canonical if the signals disagree.
What are Open Graph tags?
What is the difference between the robots meta tag and robots.txt?
robots.txt controls crawling (which URLs a crawler may fetch); the robots meta tag controls indexing of a page that was fetched.
<meta name="robots" content="noindex, follow">
The trap: a page blocked in robots.txt is never fetched, so its noindex is never seen, and the URL can still be indexed from links. To keep a page out, allow crawling and use noindex.
What is hreflang, and how do you use it for a multilingual site?
hreflang links tell search engines which URL serves which language or region, so searchers get their own language.
<link rel="alternate" hreflang="en" href="https://example.com/pricing">
<link rel="alternate" hreflang="hi" href="https://example.com/hi/pricing">
<link rel="alternate" hreflang="de" href="https://example.com/de/pricing">
<link rel="alternate" hreflang="x-default" href="https://example.com/pricing">
Every version lists all versions including itself, links must be reciprocal, and x-default is the fallback. Each version keeps its own self-referencing canonical; pointing them all at the English page drops the translations.
What is structured data, and how do you add it to a page?
Structured data describes the page's content in the schema.org vocabulary, so search engines know it is a product, an article or a recipe. Google recommends JSON-LD in a script tag.
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "HTML Interview Questions",
"datePublished": "2026-03-14",
"author": { "@type": "Organization", "name": "Coddy" }
}
</script>
It can make a page eligible for rich results but is not a ranking boost, and it must match the visible content.
HTML interview questions for experienced developers
Script loading, the rendering path, parser error recovery, resource hints, responsive images, web components and security.
What is the difference between async and defer on a script tag?
Both download the script without blocking parsing. async runs it as soon as it arrives, in any order; defer runs scripts after parsing, in document order, before DOMContentLoaded.
<script src="analytics.js" async></script>
<script src="vendor.js" defer></script>
<script src="app.js" defer></script> <!-- runs after vendor.js -->
Use defer for app code and async for independent scripts like analytics. Module scripts are deferred by default, and both attributes are ignored on inline classic scripts.
How does the browser turn HTML into pixels (the critical rendering path)?
HTML becomes the DOM and CSS the CSSOM; they combine into the render tree of visible nodes, then the browser runs layout, paint and compositing.
A classic script without async or defer pauses parsing, and stylesheets block rendering. To speed up the first render, defer scripts, inline the critical CSS and preload the hero image.
What is the difference between DOMContentLoaded and load?
DOMContentLoaded fires when the HTML is parsed and deferred scripts have run; load fires later, after images, stylesheets and iframes have loaded too.
<!DOCTYPE html>
<ol id="log"></ol>
<script>
const log = (msg) => {
const li = document.createElement('li');
li.textContent = msg + ' at ' + Math.round(performance.now()) + ' ms';
document.getElementById('log').append(li);
};
log('inline script');
document.addEventListener('DOMContentLoaded', () => log('DOMContentLoaded'));
window.addEventListener('load', () => log('load'));
</script>Start DOM code on DOMContentLoaded (or with defer); waiting for load delays the app until every image arrives.
What does the browser do with invalid HTML like a <div> inside a <p>?
It never shows an error; the parser follows defined recovery rules. A <div> start tag closes an open <p>, so the div ends up after the paragraph.
<!DOCTYPE html>
<div id="box"><p>One<div>Two</div></p><table><tr><td>Cell</td></tr></table></div>
<p>What the parser built:</p>
<pre id="out" style="white-space: pre-wrap;"></pre>
<script>
document.getElementById('out').textContent = document.getElementById('box').innerHTML;
</script>The result is <p>One</p><div>Two</div><p></p>: the stray </p> makes an empty paragraph, and the table gets a <tbody> you never wrote, so table > tr matches nothing. The parser keeps a stack of open elements to decide what closes what.
Can an <a> element contain a <div>?
Yes, since HTML5. <a> has a transparent content model: it may contain whatever its parent may contain, minus interactive content (another link, a button, an input). So a link wrapping a card is valid inside a <div> but not inside a <p>, which accepts only phrasing content.
<!DOCTYPE html>
<style>
.card { display: block; max-width: 260px; padding: 8px 12px; border: 1px solid #cbd5e1; border-radius: 8px; color: inherit; text-decoration: none; }
.card:hover { border-color: #3b82f6; }
</style>
<a class="card" href="#course">
<div><strong>HTML course</strong></div>
<div>40 lessons, free to start</div>
</a>
<p id="course">The whole card is one link.</p>What is the difference between preload, prefetch and preconnect?
preload fetches a resource the current page needs soon, at high priority. prefetch fetches what the next page will probably need, at low priority. preconnect opens the connection (DNS, TCP, TLS) to another origin without fetching anything.
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/hero.avif" as="image">
<link rel="prefetch" href="/checkout.js">
<link rel="preconnect" href="https://cdn.example.com">
<link rel="dns-prefetch" href="https://analytics.example.com">
preload needs as to get the right priority, and fonts need crossorigin even on the same origin or they download twice.
How do you lazy load images, and which image should not be lazy loaded?
Add loading="lazy" to <img> or <iframe> and the browser waits until it nears the viewport. Never lazy load the largest image visible on first load (usually the hero), because that delays the Largest Contentful Paint.
<img src="hero.avif" alt="..." width="1200" height="600" fetchpriority="high">
<img src="card.avif" alt="..." width="400" height="300" loading="lazy" decoding="async">
Set width and height on every image so the browser reserves the space and nothing shifts (CLS).
How do srcset, sizes and <picture> work?
srcset lists sizes of one image and sizes says how wide it will display, so the browser downloads the smallest file that is sharp enough. <picture> chooses between different images or formats.
<img src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Team at work" width="800" height="533">
<picture>
<source srcset="photo.avif" type="image/avif">
<source srcset="photo.webp" type="image/webp">
<img src="photo.jpg" alt="Team at work" width="800" height="533">
</picture>
w descriptors give each file's width; x descriptors (1x, 2x) suit fixed-size images. The <img> inside <picture> is required: it renders and carries alt.
What are Web Components and the Shadow DOM?
Web Components are browser-native reusable elements: custom elements (your own tags, defined with a class), the shadow DOM (a private tree whose styles do not leak in or out) and templates with slots.
<!DOCTYPE html>
<style>p { color: crimson; }</style>
<p>Outside: styled by the page.</p>
<user-badge name="Asha"></user-badge>
<script>
class UserBadge extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
const p = document.createElement('p');
p.textContent = 'Hello, ' + this.getAttribute('name');
const style = document.createElement('style');
style.textContent = 'p { color: teal; font-weight: bold; }';
this.shadowRoot.replaceChildren(style, p);
}
}
customElements.define('user-badge', UserBadge);
</script>The page's p { color: crimson } does not reach the paragraph inside the component. Custom element names need a hyphen, and inherited properties like color and CSS custom properties do pass into the shadow tree.
How do you embed third-party content safely with an iframe?
Add sandbox and grant only the permissions the frame needs. An empty sandbox blocks scripts, forms, popups and top-level navigation, and gives the frame a unique origin.
<iframe src="https://widget.example.com"
sandbox="allow-scripts allow-forms"
allow="fullscreen"
referrerpolicy="no-referrer"
loading="lazy"
title="Weather widget"></iframe>
Never combine allow-scripts with allow-same-origin for content from your own origin: the framed script could remove its own sandbox. To stop other sites framing yours, send Content-Security-Policy: frame-ancestors 'self'. See the iframe page.
Why is setting innerHTML with user input dangerous?
innerHTML parses the string as HTML, so user input becomes markup. Inserted <script> tags do not run, but event handler attributes do: <img src=x onerror="steal()"> runs the attacker's code. That is cross-site scripting (XSS).
<!DOCTYPE html>
<input id="name" value="<b>Asha</b> <i>Rao</i>" size="30">
<p>textContent: <span id="safe"></span></p>
<p>innerHTML: <span id="unsafe"></span></p>
<script>
const input = document.getElementById('name');
const show = () => {
document.getElementById('safe').textContent = input.value;
document.getElementById('unsafe').innerHTML = input.value;
};
input.addEventListener('input', show);
show();
</script>Use textContent for text, and sanitize any user HTML with a library such as DOMPurify.
What is progressive enhancement?
Progressive enhancement means building the core of the page in plain HTML that works everywhere, then adding CSS and JavaScript on top, so the page still works when a layer fails or loads slowly.
<form action="/search" method="get">
<input name="q" type="search" aria-label="Search">
<button>Search</button>
</form>
<!-- JavaScript can intercept this form for instant results;
without JavaScript it still submits and works. -->
Graceful degradation goes the other way: it starts from the full experience and adds fallbacks.
Preparing for the interview
How do I prepare for an HTML interview?
What HTML topics are asked to freshers?
id vs class, lists and tables, links and images with alt, forms and input types, semantic elements, and what HTML5 added. Expect to write a small form or layout, often with a few CSS questions.What is asked in an HTML interview for experienced developers?
async and defer, the rendering path, resource hints, image performance, ARIA, SEO and XSS. You may be asked to review markup and point out problems.