A practical, interview-focused guide covering 120 HTML and HTML5 questions — from document structure and semantic HTML to forms, accessibility, SEO, browser rendering, Web APIs, Web Components, and modern best practices.
This guide is useful for:
- Frontend developers preparing for HTML/HTML5 interviews
- Students and beginners learning HTML fundamentals
- Developers revising HTML before JavaScript, React, Angular, or other frontend interviews
- Experienced developers who want a quick HTML reference
For each question:
- Understand the concept instead of memorizing the answer.
- Read the example and try it in a browser.
- Practice explaining the concept in your own words.
- Prepare for follow-up questions such as why, when, and what are the trade-offs?
- Mark difficult questions for a second revision.
💡 Interview Tip: A strong answer usually includes definition → purpose → example → practical use case → important caveat.
Use the links below to jump directly to a topic.
- HTML Basics & Fundamentals
- HTML Document Structure
- DOCTYPE & Language Attributes
- Head vs Body
- Meta Tags & Metadata
- Linking CSS & JavaScript
- Comments in HTML
- Elements vs Tags vs Attributes
- Semantic HTML
- Text Formatting Tags
- Block vs Inline Elements
- Div vs Span
- Links & URLs
- Lists in HTML
- Images & Multimedia
- Forms & Input Types
- Tables
- HTML5 New Features
- HTML vs XHTML
- Web Storage (localStorage, sessionStorage, Cookies)
- Canvas vs SVG
- Script Loading: async vs defer
- Browser Rendering & Performance
- Server-Side vs Client-Side Rendering
- Browser Engines
- Accessibility & ARIA
- SEO Best Practices
- Responsive Design
- Advanced HTML5 Elements
- HTML5 APIs
- Drag and Drop
- Geolocation API
- Web Components
- HTML Entities & Encoding
- Deprecated Tags & Attributes
- Miscellaneous & Pro Tips
HTML (HyperText Markup Language) is the standard markup language used to create web pages and web applications. It structures content on the web using elements like headings, paragraphs, links, lists, and more.
Core Functionalities:
- Structuring Content — Tags like
<header>,<footer>, and<section>organize content. - Embedding Media — Native support for images, audio, and video.
- Form Handling — Interactive user inputs via
<form>,<input>, and<label>. - Hyperlinks — Navigation via
<a>tags. - Accessibility — Semantic tags improve screen reader experiences.
- Integration — Works seamlessly with CSS (styling) and JavaScript (interactivity).
💡 Note: HTML is a markup language, not a programming language. It defines structure; CSS defines appearance; JavaScript defines behavior.
HTML5 refers to the modern HTML feature set that introduced semantic elements, native multimedia, richer form controls, client-side storage, graphics, and improved accessibility. Today, HTML is maintained as a Living Standard, so it is better to think of HTML as an evolving standard rather than a series of separately versioned releases.
| Building Block | Description |
|---|---|
| Semantics | Describe content more precisely (<article>, <section>, <nav>) |
| Connectivity | Communicate with servers innovatively (WebSockets) |
| Offline & Storage | Store data client-side, work offline (localStorage, Service Workers) |
| Multimedia | Native audio & video support |
| 2D/3D Graphics | Canvas & WebGL for rich visuals |
| Performance | Better hardware utilization |
| Device Access | Use camera, microphone, geolocation |
| Styling | Enhanced CSS3 integration |
- Rich Media Support — Native
<audio>and<video>without plugins. - Improved Semantics — New tags like
<header>,<footer>,<nav>. - Offline capabilities — Modern applications can support offline experiences using Service Workers, the Cache API, and client-side storage.
- Improved Forms — New input types (
email,url,date) and validation. - Canvas & SVG Support — Dynamic graphics and scalable vectors.
Example:
<video src="video.mp4" controls></video>
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const ctx = document.getElementById('myCanvas').getContext('2d');
ctx.fillRect(10, 10, 150, 80);
</script>An HTML document has two main sections: <head> and <body>, wrapped in an <html> root element, preceded by a <!DOCTYPE html> declaration.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Web Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>Breakdown:
<!DOCTYPE html>— Tells the browser it's an HTML5 document.<html>— Root element containing everything.<head>— Metadata, title, links to CSS/JS (not visible).<body>— All visible content.
The <!DOCTYPE html> declaration tells the browser:
- The document is written in HTML5.
- Which parsing algorithm to use (standards mode).
- Ensures consistent rendering across browsers.
<!DOCTYPE html>
<html>
<head><title>Page Title</title></head>
<body><!-- Content --></body>
</html>Without an appropriate DOCTYPE, browsers may enter quirks mode, which emulates legacy browser behavior. This can change layout and CSS behavior, including historical box-model differences, and can lead to inconsistent rendering.
| Aspect | Standards Mode | Quirks Mode |
|---|---|---|
| Behavior | Follows HTML/CSS specs | Emulates legacy browsers |
| Triggered by | Correct <!DOCTYPE html> |
Missing/invalid DOCTYPE |
| CSS behavior | Standards-based | Legacy/quirks behavior may differ |
| Box model | W3C standard | Internet Explorer 5 model |
The lang attribute specifies the primary language of the document, helping:
- Screen readers pronounce content correctly.
- Search engines serve the right audience.
- Browser translation tools identify the language.
<!DOCTYPE html>
<html lang="en-US">
<head><title>Page Title</title></head>
<body>
<h1>Welcome</h1>
<p>This is a demo page.</p>
</body>
</html>Common Language Codes:
en— Englishes— Spanishen-GB— British Englishpt-BR— Brazilian Portugueseund— Unspecified language
- Use the
langattribute on<html>for each language version. - Use
hreflangin<link rel="alternate">to signal language variants. - Use language-specific URLs (e.g.,
example.com/en/about,example.com/es/sobre). - Server detects
Accept-Languageheader and serves the appropriate version.
<link rel="alternate" href="example.fr.html" hreflang="fr">
<link rel="alternate" href="example.es.html" hreflang="es">| Aspect | <head> |
<body> |
|---|---|---|
| Purpose | Metadata & resource links | Visible content |
| Visibility | Not shown to user | Displayed to user |
| Placement | Comes before <body> |
Comes after <head> |
| Common Elements | <title>, <meta>, <link>, <style>, <script> |
<header>, <p>, <img>, <form> |
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is visible content.</p>
</body>
</html>Meta tags provide metadata about an HTML document — information used by browsers, search engines, and other web services, but not displayed to users.
Key Meta Tags:
- Charset — Defines character encoding.
- Description — Summary used in search results.
- Viewport — Controls mobile rendering.
- Keywords — (Deprecated, mostly ignored by search engines).
- Author — Page author.
- Robots — Controls search engine indexing.
- Open Graph / Twitter Cards — Social media sharing optimization.
<head>
<meta charset="UTF-8">
<meta name="description" content="A concise summary of the page.">
<meta name="keywords" content="HTML, meta tags, web design, SEO">
<meta name="author" content="John Doe">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="index, follow">
<title>Sample Web Page</title>
</head>Character encoding converts bytes into characters. UTF-8 is the standard, supporting almost all characters across languages.
<meta charset="utf-8">Use the <link> tag inside the <head> section.
<link rel="stylesheet" href="path/to/style.css">rel="stylesheet"— Indicates the linked file is a stylesheet.href— Path to the CSS file (absolute or relative).
Use the <script> tag. Best practice: place at the end of <body> for performance.
<!-- External script -->
<script src="path/to/script.js"></script>
<!-- Inline script -->
<script>
console.log("Hello!");
</script>| Attribute | Behavior |
|---|---|
<script> |
Blocks HTML parsing while fetching and executing |
<script async> |
Fetched in parallel; executes as soon as ready (order not guaranteed) |
<script defer> |
Fetched in parallel; executes after HTML parsing (order preserved) |
<script src="regular.js"></script>
<script async src="analytics.js"></script>
<script defer src="main.js"></script>🎯 Best Practice: Use
deferfor scripts that need a fully parsed DOM. Useasyncfor independent scripts like analytics.
- CSS in
<head>: Enables progressive rendering; avoids flash of unstyled content (FOUC). - JS before
</body>: Prevents blocking HTML parsing; DOM is ready when scripts execute.
Exception: Use defer attribute when scripts must be in <head>.
<!-- This is a comment -->
<p>Hello, World!</p>Use cases:
- ✅ Document complex code sections
- ✅ Leave reminders for developers
- ✅ Temporarily disable code during debugging
- ❌ Don't state the obvious (e.g.,
<!-- paragraph -->)
- Tag — The markup code inside angle brackets (e.g.,
<p>or</p>). - Element — The complete package: opening tag + content + closing tag.
<!-- <p> and </p> are tags -->
<!-- The whole thing below is an element -->
<p>This is an element.</p>Attributes provide additional information about HTML elements. They appear in the opening tag as name="value" pairs.
<a href="https://example.com">Click me</a>
<img src="pic.jpg" alt="A photo" width="500">Common attributes: href, src, alt, id, class, style, title, lang.
Empty elements (also called void or self-closing elements) have no content and don't need a closing tag.
<img src="image.jpg" alt="An image">
<br>
<input type="text" placeholder="Enter name">
<hr>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">The data-* attributes let you store custom data on HTML elements, accessible via JavaScript's dataset API.
<div id="user" data-name="John Doe" data-age="25" data-role="admin"></div>
<script>
const userDiv = document.getElementById('user');
console.log(userDiv.dataset.name); // "John Doe"
console.log(userDiv.dataset.age); // "25"
console.log(userDiv.dataset.role); // "admin"
</script>Use cases:
- Storing configuration for widgets
- Saving product IDs in e-commerce
- Providing hooks for testing frameworks (Selenium, Capybara)
- Styling signifiers in CSS
Semantic tags clearly describe their meaning to both the browser and the developer. They improve accessibility, SEO, and code maintainability.
Common Semantic Tags:
| Tag | Purpose |
|---|---|
<header> |
Introductory content or navigational links |
<nav> |
Navigation links |
<main> |
Dominant content of the document |
<section> |
Themed grouping of content |
<article> |
Self-contained independent content |
<aside> |
Side content (sidebar, ads, related links) |
<footer> |
Footer content (copyright, contact) |
<figure> |
Grouped media content |
<figcaption> |
Caption for <figure> |
<mark> |
Highlighted text |
<time> |
Date/time representation |
Before vs After Semantic HTML:
<!-- ❌ Before: Non-semantic -->
<div class="header">
<div class="nav">
<a href="#">Home</a>
<a href="#">About</a>
</div>
</div>
<div class="content">
<h1>Welcome</h1>
<p>Some text.</p>
</div>
<!-- ✅ After: Semantic -->
<header>
<nav>
<a href="#">Home</a>
<a href="#">About</a>
</nav>
</header>
<main>
<section>
<h1>Welcome</h1>
<p>Some text.</p>
</section>
</main>| Element | Use Case |
|---|---|
<section> |
Groups thematically related content; usually has a heading |
<article> |
Self-contained, independently distributable content (blog post, news article) |
<div> |
Generic container; no semantic meaning (use when nothing else fits) |
<section>
<h2>Section Title</h2>
<article>
<h3>Article Title</h3>
<p>This is a self-contained article.</p>
</article>
</section>- ✅ SEO — Search engines understand content better.
- ✅ Accessibility — Screen readers navigate more easily.
- ✅ Maintainability — Code is easier to read and update.
- ✅ Lighter code — Reduces reliance on
<div>soup.
| Tag | Purpose |
|---|---|
<b> |
Visual bold styling only (no semantic meaning) |
<strong> |
Indicates importance (semantic, also bold by default) |
<p>
<b>Caution:</b> This action cannot be undone.
<strong>Urgent Notice!</strong> Save your work before proceeding.
</p>💡 Use
<strong>for semantic importance. Use CSS for purely visual bold styling.
| Tag | Purpose |
|---|---|
<em> |
Semantic emphasis (italic + meaning) |
<i> |
Visual italics only (idioms, technical terms, foreign words) |
<p>I <em>really</em> enjoyed the concert.</p>
<p>The term <i>modulo</i> comes from Latin.</p>| Tag | Purpose | Example |
|---|---|---|
<small> |
Fine print, copyright, disclaimers | <small>© 2026 Company</small> |
<s> |
Strikethrough (no longer relevant) | <s>EXPIRED123</s> |
<mark> |
Highlight text | <mark>Important</mark> |
<footer>
<small>© 2026 My Website</small>
</footer>
<p>Discount code: <s>EXPIRED123</s></p>
<p>Please <mark>schedule your appointment</mark> in advance.</p>| Feature | Block-level | Inline |
|---|---|---|
| Starts new line | Yes | No |
| Width | Full width of parent | Content width only |
| Examples | <div>, <p>, <h1>, <ul>, <li> |
<span>, <a>, <strong>, <img> |
<div>This block starts a new line.</div>
<div>Another block.</div>
<span>This inline stays</span> <span>on the same line.</span>| Aspect | <div> |
<span> |
|---|---|---|
| Display type | Block-level | Inline |
| Width | Full width of parent | Only content width |
| Use case | Grouping larger sections | Styling small portions of text |
| Semantic meaning | None | None |
<div style="background-color: lightblue; padding: 10px;">
This is a <span style="color: red;">highlighted</span> text inside a div.
</div>Use the <a> (anchor) tag with an href attribute.
<a href="https://www.example.com">Visit Example</a>- Anchor Link —
<a href="https://example.com">Link</a> - Image Link —
<a href="page.html"><img src="img.jpg"></a> - External Resource —
<link rel="stylesheet" href="style.css"> - Bookmark Link —
<a href="#section2">Jump to Section 2</a> - Image Map Link —
<area shape="rect" coords="0,0,50,50" href="page.html">
| Type | Description | Example |
|---|---|---|
| Absolute | Full path including protocol | https://www.example.com/page |
| Relative | Path relative to current page | /page or ../page |
<!-- Absolute -->
<a href="https://www.example.com/about.html">About Us</a>
<!-- Relative -->
<a href="/about.html">About Us</a>
<a href="contact.html">Contact</a>A fragment identifier (after # in a URL) points to a specific section within a page.
https://www.example.com/page#section2
Here, #section2 scrolls to the element with id="section2".
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
Open in New Tab
</a>target="_blank"— Opens in new tab.rel="noopener"— Prevents the new page from accessingwindow.opener(security).rel="noreferrer"— Doesn't send referrer information.
| Tag | Purpose | Clickable? |
|---|---|---|
<a> |
Hyperlink to another page/section | Yes |
<link> |
Links external resources (CSS, favicon) to document | No |
| List Type | Tag | Use Case |
|---|---|---|
| Ordered List | <ol> |
Numbered items |
| Unordered List | <ul> |
Bulleted items |
| Description List | <dl> |
Term-description pairs |
<ol>
<li>First item</li>
<li>Second item</li>
</ol>
<ul>
<li>Bullet point</li>
<li>Another point</li>
</ul>
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language</dd>
</dl><img src="mountain.jpg" alt="A beautiful mountain scene">src— Path to the image file.alt— Alternative text for accessibility and SEO.
Why alt matters:
- Screen readers describe the image to visually impaired users.
- Search engines index images better.
- Shows when image fails to load.
<video controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser doesn't support videos.
</video>controls— Adds play/pause/volume controls.- Multiple
<source>tags provide format fallbacks.
Adds playback controls (play, pause, volume, fullscreen) to media elements like <video> and <audio>.
Automatically plays media when the page loads.
<video autoplay muted></video>
⚠️ Most browsers block autoplay with sound. Usemutedto allow it.
Adds subtitles, captions, or descriptions to media.
<video controls>
<source src="movie.mp4" type="video/mp4">
<track kind="subtitles" src="subtitles.vtt" srclang="en">
</video>Provides multiple image sources for responsive design.
<picture>
<source media="(min-width: 800px)" srcset="big.jpg">
<source srcset="small.webp" type="image/webp">
<img src="small.jpg" alt="Cool image">
</picture>srcset lets the browser choose the best image based on device resolution.
<img srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 2000w"
src="small.jpg" alt="Responsive image">The browser calculates the best image to load based on viewport width and device pixel ratio.
Wrap the <img> inside an <a> tag.
<a href="https://example.com">
<img src="logo.png" alt="Click to visit">
</a><form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>| Type | Description |
|---|---|
email |
Email address |
url |
URL |
tel |
Telephone number |
number |
Numeric input |
date |
Date picker |
time |
Time picker |
datetime-local |
Date and time |
month |
Month picker |
week |
Week picker |
color |
Color picker |
range |
Slider |
search |
Search field |
<input type="email" name="email" required>
<input type="date" name="birthday">
<input type="color" value="#ff0000">
<input type="range" min="0" max="100" value="50">| Attribute | Purpose |
|---|---|
required |
Field must be filled |
placeholder |
Hint text |
autofocus |
Auto-focus on page load |
autocomplete |
Enable/disable browser autocomplete |
min / max |
Min/max values |
step |
Increment step |
pattern |
Regex validation |
novalidate |
Disable browser validation |
<form novalidate>
<input type="text" name="phone" pattern="[0-9]{10}" required
placeholder="10 digit number">
<input type="number" name="age" min="18" max="60" step="1">
<button type="submit">Submit</button>
</form><label for="fruits">Pick a fruit:</label>
<select id="fruits" name="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry" selected>Cherry</option>
</select>| Feature | <select> |
<datalist> |
|---|---|---|
| User input | Must choose from options | Can type or choose |
| Flexibility | Limited to options | Free text + suggestions |
<!-- Select: must pick one -->
<select name="browser">
<option value="firefox">Firefox</option>
<option value="chrome">Chrome</option>
</select>
<!-- Datalist: suggestions with free text -->
<input type="text" list="browsers">
<datalist id="browsers">
<option value="Firefox">
<option value="Chrome">
</datalist><!-- Radio buttons (single choice) -->
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<!-- Checkboxes (multiple choices) -->
<input type="checkbox" id="news" name="newsletter" checked>
<label for="news">Subscribe to newsletter</label>The <label> tag provides a text description for form inputs. Linking via for and id improves accessibility — clicking the label focuses the input.
<label for="name">Name:</label>
<input type="text" id="name" name="name"><fieldset> groups related form fields; <legend> provides a caption.
<fieldset>
<legend>Personal Details</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</fieldset>Displays the result of a calculation or user action.
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="number" id="a" value="0"> +
<input type="number" id="b" value="0"> =
<output name="result" for="a b">0</output>
</form>The enctype attribute specifies how form data is encoded when a form is submitted using POST.
| Value | Use Case |
|---|---|
application/x-www-form-urlencoded |
Default (text data) |
multipart/form-data |
File uploads |
text/plain |
Plain text (rarely used) |
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>| Feature | GET | POST |
|---|---|---|
| Data in URL | Yes (visible) | No (in body) |
| Security | Not inherently secure; use HTTPS | Not inherently secure; use HTTPS |
| Data limit | Limited by URL length and browser/server constraints | Generally supports much larger payloads, subject to server and infrastructure limits |
| Use case | Search, retrieval | Submissions, uploads |
| Bookmarkable | Yes | No |
Overrides the form's action for a specific submit button.
<form action="/default-submit">
<button type="submit">Default Submit</button>
<button type="submit" formaction="/alt-submit">Alternative Submit</button>
</form><table>
<caption>Sales Chart</caption>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Book</td>
<td>$10</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$10</td>
</tr>
</tfoot>
</table>Specifies how many columns a cell should span.
<table border="1">
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td colspan="2">Spans 2 columns</td>
</tr>
</table>| Tag | Purpose |
|---|---|
<table> |
Defines a table |
<caption> |
Table title |
<thead> |
Header section |
<tbody> |
Body section |
<tfoot> |
Footer section |
<tr> |
Table row |
<th> |
Header cell |
<td> |
Data cell |
<colgroup> |
Group of columns |
<col> |
Column properties |
The <canvas> element is used to draw graphics on the fly using JavaScript.
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#7cce2b';
ctx.fillRect(0, 0, 150, 80);
</script>Creates an expandable disclosure widget.
<details>
<summary>Click to expand</summary>
<p>Hidden content goes here.</p>
</details><progress value="50" max="100">50%</progress>Indicates a numeric value within a range.
<meter value="0.6">60%</meter>
<meter value="6" min="0" max="10">6 out of 10</meter>Represents a specific time or date.
<p>The concert is on <time datetime="2026-08-21">Christmas Day</time>.</p>Creates native modal dialogs with built-in accessibility.
<dialog id="myDialog">
<p>This is a modal dialog.</p>
<button id="closeBtn">Close</button>
</dialog>
<button id="openBtn">Open Dialog</button>
<script>
const dialog = document.getElementById("myDialog");
document.getElementById("openBtn").onclick = () => dialog.showModal();
document.getElementById("closeBtn").onclick = () => dialog.close();
</script>Holds HTML content that's not rendered until cloned via JavaScript.
<template id="cardTemplate">
<div class="card">
<h3>User Name</h3>
<p>Template content.</p>
</div>
</template>
<script>
const template = document.getElementById("cardTemplate");
const clone = template.content.cloneNode(true);
document.body.appendChild(clone);
</script>Forces the browser to download a linked resource instead of navigating to it.
<a href="file.pdf" download>Download PDF</a>
<a href="report.pdf" download="annual-report.pdf">Download Report</a>Q69. What is the hidden attribute?
Hides an element from display.
<p hidden>This text is not shown.</p>Makes any element editable by the user.
<div contenteditable="true">Click to edit this text.</div>| Feature | HTML | XHTML |
|---|---|---|
| Syntax | Lenient | Strict (XML-based) |
| Closing tags | Optional for some | Required for all |
| Case sensitivity | Case-insensitive | Case-sensitive (lowercase) |
| Attribute values | Can be minimized | Must be quoted |
| Document structure | Forgiving | Strict, well-formed |
<!-- HTML -->
<img src="image.jpg">
<input type="checkbox" checked>
<!-- XHTML -->
<img src="image.jpg" />
<input type="checkbox" checked="checked" />| Feature | Cookie | localStorage | sessionStorage |
|---|---|---|---|
| Initiator | Client/Server | Client | Client |
| Expiry | Manually set | Forever | On tab close |
| Capacity | ~4KB | ~5MB | ~5MB |
| Sent with HTTP requests | Yes | No | No |
| Persistent across sessions | Depends | Yes | No |
| Accessibility | Any window | Any window | Same tab only |
// localStorage
localStorage.setItem('key', 'value');
localStorage.getItem('key');
// sessionStorage
sessionStorage.setItem('key', 'value');
sessionStorage.getItem('key');Yes, it throws a QuotaExceededError.
try {
localStorage.setItem('key', 'largeValue');
} catch (e) {
console.log('Exception: ' + e); // QuotaExceededError
}| Feature | SVG | Canvas |
|---|---|---|
| Type | Vector-based | Raster-based (pixels) |
| DOM | Part of DOM | Single element |
| Scalability | Scales without quality loss | Pixelates when scaled |
| Modification | Via script and CSS | Via script only |
| Performance | Better with fewer objects | Better with many objects |
| Best for | Icons, logos, charts | Games, complex animations |
SVG Example:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="red"/>
</svg>Canvas Example:
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
const ctx = document.getElementById('myCanvas').getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 50);
</script>| Attribute | Parsing | Download | Execution |
|---|---|---|---|
<script> |
Blocked | Then executes | Resumes parsing |
<script async> |
Continues | In parallel | Executes immediately when ready |
<script defer> |
Continues | In parallel | Executes after parsing completes (in order) |
<!-- Runs immediately, blocks parsing -->
<script src="critical.js"></script>
<!-- Runs as soon as downloaded, may be out of order -->
<script async src="analytics.js"></script>
<!-- Runs after HTML is parsed, preserves order -->
<script defer src="main.js"></script>The Document Object Model (DOM) is a cross-platform API that treats HTML documents as a tree structure of nodes. These nodes can be manipulated with languages like JavaScript.
document
└── html
├── head
│ ├── title
│ └── meta
└── body
├── h1
├── p
└── div
- DOM — Parse HTML into Document Object Model.
- CSSOM — Parse CSS into CSS Object Model.
- Render Tree — Combine DOM and CSSOM.
- Layout — Calculate element positions and sizes.
- Paint — Fill in pixels (colors, text, images).
- Composite — Draw layers to screen in correct order.
The sequence of steps the browser takes to render the initial view:
- Construct DOM Tree
- Construct CSSOM Tree
- Run JavaScript (parser blocking)
- Create Render Tree
- Generate Layout
- Paint
- Layout — Calculates element size and position.
- Painting — Fills in pixels (text, colors, borders, shadows).
- Compositing — Combines painted layers in correct order on screen.
- Minimize HTTP Requests — Combine CSS/JS files.
- Use a CDN — Serve content from nearby servers.
- Optimize Images — Compress, resize, use modern formats (WebP).
- Put Scripts at the Bottom — Or use
defer/async. - Use Gzip Compression — Reduces response size ~70%.
- Add Expires Headers — Enable browser caching.
- Minify CSS/JS — Remove whitespace and comments.
- Use CSS Sprites — Combine background images.
- Reduce DNS Lookups — Minimize different domains.
- Avoid Redirects — Each redirect adds a request.
- Lazy Load Images —
loading="lazy". - Make AJAX Cacheable — Use GET for idempotent requests.
Techniques to render content as quickly as possible:
- Lazy loading — Load images when scrolled into view.
- Above-the-fold prioritization — Render visible content first.
- Async HTML fragments — Flush HTML chunks as they're ready.
<img src="image.jpg" loading="lazy" alt="Lazy loaded image">Forcing browsers to download fresh files by changing the URL.
<script src="js/script.js?v=2"></script>| Aspect | SSR (Server-Side Rendering) | CSR (Client-Side Rendering) |
|---|---|---|
| Initial load | Faster (HTML ready) | Slower (waits for JS) |
| SEO | Better (crawlers see content) | Worse (content loaded via JS) |
| User experience | Quick first view | Wait for full JS load |
| Server load | Higher | Lower |
| Browser | Layout Engine | JavaScript Engine |
|---|---|---|
| Chrome | Blink | V8 |
| Firefox | Gecko | SpiderMonkey |
| Safari | WebKit | JavaScriptCore (Nitro) |
| Edge (legacy) | EdgeHTML | Chakra |
| Internet Explorer | Trident | Chakra |
| Opera (legacy) | Presto | Carakan |
ARIA (Accessible Rich Internet Applications) adds attributes to make dynamic web content accessible to screen readers and assistive technologies.
Common ARIA attributes:
| Attribute | Purpose |
|---|---|
aria-label |
Descriptive label for elements |
aria-describedby |
References element with extra info |
aria-required |
Marks mandatory form fields |
aria-expanded |
Indicates collapsible state |
aria-disabled |
Indicates disabled state |
aria-checked |
Indicates checked state |
aria-hidden |
Hides from assistive tech |
aria-haspopup |
Indicates popup presence |
<button aria-label="Close dialog">X</button>
<div role="alert">Error: Invalid input</div>
<input type="text" aria-required="true">- ✅ Use semantic HTML tags (
<nav>,<header>,<main>). - ✅ Add
alttext to images. - ✅ Use proper heading hierarchy (
<h1>→<h6>). - ✅ Label all form fields.
- ✅ Use ARIA attributes for dynamic content.
- ✅ Ensure keyboard navigation works.
- ✅ Maintain color contrast.
- Use semantic elements (
<article>,<section>,<nav>). - Add a descriptive
<title>element. - Provide a useful
<meta name="description">. - Add appropriate
alttext to informative images. - Use a logical heading hierarchy.
- Use
hreflangwhen you have genuine multilingual or regional variants. - Optimize script loading with appropriate techniques such as
defer. - Add relevant structured data when it matches the page content.
<head>
<meta name="description" content="Learn web development tips">
<title>Web Development Guide</title>
</head>Microdata adds structured data using itemscope, itemtype, and itemprop to help search engines understand content.
<div itemscope itemtype="https://schema.org/Person">
<span itemprop="name">John Doe</span>
<span itemprop="jobTitle">Developer</span>
</div><h1>— Main page heading; use a clear, logical heading structure rather than treating a single<h1>as a strict technical requirement.<h2>— Major sections.<h3>— Subsections.
Proper heading hierarchy helps:
- Search engines understand content structure.
- Screen readers navigate the page.
- Users scan content quickly.
- Set the viewport:
<meta name="viewport" content="width=device-width, initial-scale=1.0">- Use responsive images:
<img src="img.png" style="width:100%;">- Use the
<picture>element:
<picture>
<source srcset="small.jpg" media="(max-width: 600px)">
<source srcset="large.jpg" media="(min-width: 601px)">
<img src="default.jpg" alt="Image">
</picture>- Use viewport units for text:
<h1 style="font-size:10vw">Hello World</h1>- Use media queries in CSS:
@media screen and (max-width: 800px) {
.container { width: 100%; }
}| Approach | Strategy | Media Query |
|---|---|---|
| Desktop-first | Start with desktop styles, override for smaller | max-width |
| Mobile-first | Start with mobile styles, enhance for larger | min-width |
Embeds another webpage inside the current page.
<iframe src="https://example.com" width="600" height="400" title="Embedded Page"></iframe>Restricts what the embedded content can do for security.
<iframe src="page.html" sandbox></iframe>Restrictions include: no JavaScript, no form submission, no popups.
Sets a default base URL for all relative URLs on the page.
<head>
<base href="https://example.com/">
</head>
<a href="page.html">Link</a>
<!-- Goes to https://example.com/page.html -->Contains contact information for the page author or owner.
<address>
Jane Doe<br>
<a href="mailto:jane@example.com">jane@example.com</a><br>
456 Park Ave, USA
</address>Indicates a long quotation from another source.
<blockquote cite="https://example.com/">
A really inspiring quote from somewhere.
</blockquote>Provides fallback content when JavaScript is disabled or unsupported.
<script>
document.write("JavaScript is on!");
</script>
<noscript>JavaScript is off. Please enable it for full experience.</noscript>Attributes that can be used on any HTML element.
| Attribute | Purpose |
|---|---|
id |
Unique identifier |
class |
One or more class names |
title |
Tooltip text |
hidden |
Hides element |
tabindex |
Keyboard focus order |
contenteditable |
Makes element editable |
data-* |
Custom data storage |
lang |
Language of content |
style |
Inline CSS |
| API | Purpose |
|---|---|
| Geolocation | Get user's location |
| Web Storage | localStorage & sessionStorage |
| WebSocket | Two-way communication with server |
| Canvas | 2D graphics drawing |
| Drag and Drop | Native drag-and-drop |
| Web Workers | Background scripts |
| Application Cache | Offline app support (deprecated) |
| Page Visibility | Detect if page is visible |
| Fullscreen API | Enter/exit fullscreen |
| Battery Status | Battery info |
| Vibration API | Vibrate device |
| Network Information | Connection details |
| High Resolution Time | Precise timing |
| User Timing | Performance measurement |
Enables two-way interactive communication between browser and server.
const socket = new WebSocket('ws://localhost:8080/');
socket.addEventListener('open', function(event) {
socket.send('Hello Server!');
});
socket.addEventListener('message', function(event) {
console.log('Message from server:', event.data);
});Allows users to share their location with web applications.
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(pos) {
console.log("Latitude:", pos.coords.latitude);
console.log("Longitude:", pos.coords.longitude);
});
}HTML5 provides native drag-and-drop via DOM events.
| Event | Description |
|---|---|
dragstart |
Fires when dragging starts |
drag |
Fires repeatedly during drag |
dragenter |
Fires when dragged item enters target |
dragover |
Fires when mouse moves over target |
dragleave |
Fires when item leaves target |
drop |
Fires when item is dropped |
dragend |
Fires when drag operation ends |
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
const data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"
style="width:200px;height:200px;border:1px solid black;"></div>
<img id="drag1" src="logo.gif" draggable="true"
ondragstart="drag(event)" width="100" height="50">The Geolocation API lets users share their location. For privacy, the user must give permission.
navigator.geolocation.getCurrentPosition(
function(position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
},
function(error) {
console.log("Error:", error.message);
}
);Web Components are reusable custom HTML elements with encapsulated styles and behavior.
They use:
- Custom Elements — Define your own tags.
- Shadow DOM — Encapsulated DOM and styles.
- HTML Templates — Reusable markup in
<template>.
<custom-element>Cool stuff</custom-element>
<script>
class CustomElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = '<p>My Custom Component</p>';
}
}
customElements.define('custom-element', CustomElement);
</script>HTML entities are codes used to display reserved or special characters.
| Character | Entity |
|---|---|
< |
< |
> |
> |
& |
& |
© |
© |
® |
® |
™ |
™ |
@ |
@ |
§ |
§ |
(non-breaking space) |
|
<p>5 < 10 is true.</p>
<p>© 2026 My Company</p>URL encoding converts characters into a format that can be transmitted over the web. Special characters are replaced with % followed by two hexadecimal digits.
| Character | Encoded |
|---|---|
| Space | %20 or + |
$ |
%24 |
& |
%26 |
+ |
%2B |
/ |
%2F |
| Tag | Replacement |
|---|---|
<acronym> |
<abbr> |
<applet> |
<object> |
<basefont> |
CSS |
<big> |
CSS |
<center> |
CSS |
<dir> |
<ul> |
<font> |
CSS |
<frame> / <frameset> |
<iframe> or CSS |
<noframes> |
— |
<s> |
<del> or CSS |
<strike> |
<del> or CSS |
<tt> |
CSS |
<u> |
CSS |
The <keygen> element was used to generate encryption keys for forms. It's deprecated and should not be used.
A deprecated HTML5 feature for offline web apps. Use Service Workers instead.
<!-- Deprecated approach -->
<html manifest="example.appcache">- WebSQL is deprecated and only supported in Chrome/Safari.
- IndexedDB is the modern standard for large-scale client-side storage with:
- Asynchronous API
- Transactional database model
- Indexing for fast searches
- Better browser support
The Web Hypertext Application Technology Working Group (WHATWG) is a community that maintains HTML standards. Founded in 2004 by Apple, Mozilla, and Opera to address W3C's direction with XHTML.
Modernizr is a JavaScript library that detects HTML5 and CSS3 feature support in browsers, enabling feature detection (better than browser sniffing).
if (Modernizr.canvas) {
// Browser supports canvas
} else {
// Provide fallback
}Cross-Origin Resource Sharing (CORS) is a W3C spec allowing cross-domain communication from the browser. It enables secure cross-domain data transfers via HTTP headers.
| Concept | Approach |
|---|---|
| Progressive Enhancement | Start with a basic, functional experience; enhance for modern browsers |
| Graceful Degradation | Build for modern browsers; provide fallbacks for older ones |
Controls keyboard focus order.
| Value | Behavior |
|---|---|
0 |
Focusable in natural order |
1 (positive) |
Custom focus order (use sparingly) |
-1 |
Focusable only via JavaScript, skipped in tab order |
<div tabindex="0">Focusable div</div>
<button tabindex="1">First button</button>A simple tooltip-like browser hint can be provided with the title attribute. For accessible, interactive tooltips, use an appropriate accessible pattern instead of relying on title alone.
<span title="This is a tooltip">Hover over me</span><p>Line 1<br>Line 2</p>Q118. How to create a hidden input field?
<input type="hidden" name="userID" value="12345">Q119. What is the difference between display: none and visibility: hidden?
| Property | Effect |
|---|---|
display: none |
Element removed from layout; takes no space |
visibility: hidden |
Element invisible but still takes up space |
Use:
- Service Workers — Modern approach for offline caching.
- Cache API — Store resources.
- localStorage/sessionStorage — Store data.
- IndexedDB — Large-scale storage.
Before your interview, make sure you can confidently explain:
- ✅ HTML document structure and DOCTYPE
- ✅ Semantic HTML and why it matters
- ✅ Difference between block and inline elements
- ✅
<div>vs<span>vs<section>vs<article> - ✅ Forms, input types, and validation
- ✅ Tables and accessibility
- ✅ Canvas vs SVG
- ✅ localStorage vs sessionStorage vs cookies
- ✅
asyncvsdeferin scripts - ✅ Web storage and offline capabilities
- ✅ ARIA and accessibility
- ✅ SEO best practices
- ✅ Responsive design with
<picture>and viewport - ✅ HTML5 APIs (Geolocation, WebSocket, etc.)
- ✅ Deprecated tags and modern alternatives
Before the interview, make sure you can explain the following without looking at notes:
- Document structure,
<!DOCTYPE html>,lang,<head>, and<body> - Elements, tags, attributes, and void elements
- Semantic HTML and common semantic elements
- Links, URLs, lists, images, and multimedia
- Input types and validation
label,fieldset,legend,select, anddatalistGETvsPOSTenctypeand file uploads
- DOM, CSSOM, render tree, layout, paint, and compositing
- Critical Rendering Path
asyncvsdefer- Image optimization and lazy loading
- SSR vs CSR
- Semantic HTML
alttext and form labels- Keyboard accessibility
- ARIA and when to use it
- Heading hierarchy
- Metadata and structured data
- Web Storage
- Canvas vs SVG
- WebSocket and Geolocation
- Drag and Drop
- Web Components
- Deprecated APIs and modern alternatives
🎯 Best Practice: For every topic, prepare one definition, one code example, one real-world use case, and one common interview follow-up.
- MDN Web Docs - HTML
- W3C HTML Specification
- WHATWG HTML Living Standard
- HTML5 Doctor
- Web Accessibility Initiative (WAI)
This guide covers everything from basic HTML structure to advanced HTML5 features. Master these concepts, practice with real examples, and you'll be well-prepared for any HTML5 interview.
💡 Pro Tip: Don't just memorize answers — understand the why behind each concept. Interviewers love follow-up questions!
Good luck with your interview! 🚀
Last updated: 2026 | Total Questions: 120 | Difficulty: Beginner to Advanced