Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

HTML5 Interview Questions & Answers

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.

🎯 Who This Guide Is For

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

🧭 How to Use This Guide

For each question:

  1. Understand the concept instead of memorizing the answer.
  2. Read the example and try it in a browser.
  3. Practice explaining the concept in your own words.
  4. Prepare for follow-up questions such as why, when, and what are the trade-offs?
  5. Mark difficult questions for a second revision.

💡 Interview Tip: A strong answer usually includes definition → purpose → example → practical use case → important caveat.


📑 Table of Contents

Use the links below to jump directly to a topic.

  1. HTML Basics & Fundamentals
  2. HTML Document Structure
  3. DOCTYPE & Language Attributes
  4. Head vs Body
  5. Meta Tags & Metadata
  6. Linking CSS & JavaScript
  7. Comments in HTML
  8. Elements vs Tags vs Attributes
  9. Semantic HTML
  10. Text Formatting Tags
  11. Block vs Inline Elements
  12. Div vs Span
  13. Links & URLs
  14. Lists in HTML
  15. Images & Multimedia
  16. Forms & Input Types
  17. Tables
  18. HTML5 New Features
  19. HTML vs XHTML
  20. Web Storage (localStorage, sessionStorage, Cookies)
  21. Canvas vs SVG
  22. Script Loading: async vs defer
  23. Browser Rendering & Performance
  24. Server-Side vs Client-Side Rendering
  25. Browser Engines
  26. Accessibility & ARIA
  27. SEO Best Practices
  28. Responsive Design
  29. Advanced HTML5 Elements
  30. HTML5 APIs
  31. Drag and Drop
  32. Geolocation API
  33. Web Components
  34. HTML Entities & Encoding
  35. Deprecated Tags & Attributes
  36. Miscellaneous & Pro Tips

1. HTML Basics & Fundamentals

Q1. What does HTML stand for and what is its purpose?

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.


Q2. What is HTML5?

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.


Q3. What are the building blocks of HTML5?

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

Q4. Give 5 advantages of HTML5

  1. Rich Media Support — Native <audio> and <video> without plugins.
  2. Improved Semantics — New tags like <header>, <footer>, <nav>.
  3. Offline capabilities — Modern applications can support offline experiences using Service Workers, the Cache API, and client-side storage.
  4. Improved Forms — New input types (email, url, date) and validation.
  5. 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>

2. HTML Document Structure

Q5. Describe the basic structure of an HTML document

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.

3. DOCTYPE & Language Attributes

Q6. What does <!DOCTYPE html> do?

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>

Q7. What happens when DOCTYPE is not given?

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.


Q8. What is the difference between standards mode and quirks mode?

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

Q9. What does the lang attribute do?

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 — English
  • es — Spanish
  • en-GB — British English
  • pt-BR — Brazilian Portuguese
  • und — Unspecified language

Q10. How do you serve a page in multiple languages?

  1. Use the lang attribute on <html> for each language version.
  2. Use hreflang in <link rel="alternate"> to signal language variants.
  3. Use language-specific URLs (e.g., example.com/en/about, example.com/es/sobre).
  4. Server detects Accept-Language header and serves the appropriate version.
<link rel="alternate" href="example.fr.html" hreflang="fr">
<link rel="alternate" href="example.es.html" hreflang="es">

4. Head vs Body

Q11. What is the difference between <head> and <body>?

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>

5. Meta Tags & Metadata

Q12. What is the purpose of meta tags?

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>

Q13. What is Character Encoding?

Character encoding converts bytes into characters. UTF-8 is the standard, supporting almost all characters across languages.

<meta charset="utf-8">

6. Linking CSS & JavaScript

Q14. How do you link a CSS file to an HTML document?

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).

Q15. How do you link a JavaScript file?

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>

Q16. Describe the difference between <script>, <script async>, and <script defer>

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 defer for scripts that need a fully parsed DOM. Use async for independent scripts like analytics.


Q17. Why put CSS in <head> and JS before </body>?

  • 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>.


7. Comments in HTML

Q18. How do you add comments in HTML?

<!-- 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 -->)

8. Elements vs Tags vs Attributes

Q19. What is the difference between HTML tags and elements?

  • 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>

Q20. What are attributes in HTML?

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.


Q21. What are Empty/Void elements?

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">

Q22. What are data-* attributes?

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

9. Semantic HTML

Q23. What are semantic HTML tags?

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>

Q24. When should you use <section>, <div>, or <article>?

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>

Q25. Why use semantic tags?

  • 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.

10. Text Formatting Tags

Q26. Difference between <b> and <strong>?

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.


Q27. When to use <em> over <i>?

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>

Q28. Purpose of <small>, <s>, and <mark> tags?

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>&copy; 2026 My Website</small>
</footer>
<p>Discount code: <s>EXPIRED123</s></p>
<p>Please <mark>schedule your appointment</mark> in advance.</p>

11. Block vs Inline Elements

Q29. What are Block-level and Inline elements?

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>

12. Div vs Span

Q30. What is the difference between <div> and <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>

13. Links & URLs

Q31. How do you create a hyperlink?

Use the <a> (anchor) tag with an href attribute.

<a href="https://www.example.com">Visit Example</a>

Q32. What are the 5 types of links in HTML?

  1. Anchor Link<a href="https://example.com">Link</a>
  2. Image Link<a href="page.html"><img src="img.jpg"></a>
  3. External Resource<link rel="stylesheet" href="style.css">
  4. Bookmark Link<a href="#section2">Jump to Section 2</a>
  5. Image Map Link<area shape="rect" coords="0,0,50,50" href="page.html">

Q33. Difference between Absolute and Relative URLs?

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>

Q34. What is a Fragment Identifier?

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".


Q35. How to make a link open in a new tab safely?

<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 accessing window.opener (security).
  • rel="noreferrer" — Doesn't send referrer information.

Q36. Difference between <link> and <a> tags?

Tag Purpose Clickable?
<a> Hyperlink to another page/section Yes
<link> Links external resources (CSS, favicon) to document No

14. Lists in HTML

Q37. What are the different types of lists?

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>

15. Images & Multimedia

Q38. What is the <img> tag and the alt attribute?

<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.

Q39. How to embed a video in HTML5?

<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.

Q40. What is the controls attribute?

Adds playback controls (play, pause, volume, fullscreen) to media elements like <video> and <audio>.


Q41. What is the autoplay attribute?

Automatically plays media when the page loads.

<video autoplay muted></video>

⚠️ Most browsers block autoplay with sound. Use muted to allow it.


Q42. What is the <track> element?

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>

Q43. What is the <picture> element?

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>

Q44. Why use the srcset attribute?

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.


Q45. How to make an image clickable?

Wrap the <img> inside an <a> tag.

<a href="https://example.com">
  <img src="logo.png" alt="Click to visit">
</a>

16. Forms & Input Types

Q46. How do you create a form in HTML5?

<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>

Q47. What are the new input types in HTML5?

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">

Q48. What are common form attributes?

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>

Q49. How do you create a dropdown list?

<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>

Q50. Difference between <select> and <datalist>?

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>

Q51. How do you create radio buttons and checkboxes?

<!-- 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>

Q52. What is the <label> tag and why is it important?

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">

Q53. What is the <fieldset> and <legend> tags?

<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>

Q54. What is the <output> tag?

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>

Q55. What is enctype in forms?

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>

Q56. Difference between GET and POST methods?

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

Q57. What is the formaction attribute?

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>

17. Tables

Q58. How do you create a table in HTML5?

<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>

Q59. What is the colspan attribute?

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>

Q60. Common table tags

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

18. HTML5 New Features

Q61. What is the <canvas> element?

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>

Q62. What is the <details> and <summary> element?

Creates an expandable disclosure widget.

<details>
  <summary>Click to expand</summary>
  <p>Hidden content goes here.</p>
</details>

Q63. How do you create a progress bar?

<progress value="50" max="100">50%</progress>

Q64. What is the <meter> tag?

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>

Q65. What is the <time> element?

Represents a specific time or date.

<p>The concert is on <time datetime="2026-08-21">Christmas Day</time>.</p>

Q66. What is the <dialog> element?

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>

Q67. What is the <template> element?

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>

Q68. What is the download attribute?

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>

Q70. What is the contenteditable attribute?

Makes any element editable by the user.

<div contenteditable="true">Click to edit this text.</div>

19. HTML vs XHTML

Q71. What is the difference between HTML and XHTML?

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" />

20. Web Storage (localStorage, sessionStorage, Cookies)

Q72. Difference between cookies, sessionStorage, and localStorage?

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');

Q73. Does localStorage throw an error after reaching maximum limits?

Yes, it throws a QuotaExceededError.

try {
  localStorage.setItem('key', 'largeValue');
} catch (e) {
  console.log('Exception: ' + e); // QuotaExceededError
}

21. Canvas vs SVG

Q74. What is the difference between SVG and Canvas?

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>

22. Script Loading: async vs defer

Q75. Detailed comparison of <script>, <script async>, <script defer>

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>

23. Browser Rendering & Performance

Q76. What is the DOM?

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

Q77. How does the browser rendering engine work?

  1. DOM — Parse HTML into Document Object Model.
  2. CSSOM — Parse CSS into CSS Object Model.
  3. Render Tree — Combine DOM and CSSOM.
  4. Layout — Calculate element positions and sizes.
  5. Paint — Fill in pixels (colors, text, images).
  6. Composite — Draw layers to screen in correct order.

Q78. What is the Critical Rendering Path?

The sequence of steps the browser takes to render the initial view:

  1. Construct DOM Tree
  2. Construct CSSOM Tree
  3. Run JavaScript (parser blocking)
  4. Create Render Tree
  5. Generate Layout
  6. Paint

Q79. Explain the difference between layout, painting, and compositing

  • Layout — Calculates element size and position.
  • Painting — Fills in pixels (text, colors, borders, shadows).
  • Compositing — Combines painted layers in correct order on screen.

Q80. Ways to improve website performance

  1. Minimize HTTP Requests — Combine CSS/JS files.
  2. Use a CDN — Serve content from nearby servers.
  3. Optimize Images — Compress, resize, use modern formats (WebP).
  4. Put Scripts at the Bottom — Or use defer/async.
  5. Use Gzip Compression — Reduces response size ~70%.
  6. Add Expires Headers — Enable browser caching.
  7. Minify CSS/JS — Remove whitespace and comments.
  8. Use CSS Sprites — Combine background images.
  9. Reduce DNS Lookups — Minimize different domains.
  10. Avoid Redirects — Each redirect adds a request.
  11. Lazy Load Imagesloading="lazy".
  12. Make AJAX Cacheable — Use GET for idempotent requests.

Q81. What is progressive rendering?

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">

Q82. What is cache busting?

Forcing browsers to download fresh files by changing the URL.

<script src="js/script.js?v=2"></script>

24. Server-Side vs Client-Side Rendering

Q83. What are the benefits of SSR over CSR?

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

25. Browser Engines

Q84. Comparison of browser engines?

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

26. Accessibility & ARIA

Q85. What are ARIA and screen readers?

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">

Q86. How to make a website accessible?

  • ✅ Use semantic HTML tags (<nav>, <header>, <main>).
  • ✅ Add alt text 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.

27. SEO Best Practices

Q87. How to make HTML better for SEO?

  1. Use semantic elements (<article>, <section>, <nav>).
  2. Add a descriptive <title> element.
  3. Provide a useful <meta name="description">.
  4. Add appropriate alt text to informative images.
  5. Use a logical heading hierarchy.
  6. Use hreflang when you have genuine multilingual or regional variants.
  7. Optimize script loading with appropriate techniques such as defer.
  8. 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>

Q88. What is microdata?

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>

Q89. What is the role of heading tags in SEO?

  • <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.

28. Responsive Design

Q90. How to make a page responsive?

  1. Set the viewport:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  1. Use responsive images:
<img src="img.png" style="width:100%;">
  1. 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>
  1. Use viewport units for text:
<h1 style="font-size:10vw">Hello World</h1>
  1. Use media queries in CSS:
@media screen and (max-width: 800px) {
  .container { width: 100%; }
}

Q91. What is desktop-first vs mobile-first design?

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

29. Advanced HTML5 Elements

Q92. What is the <iframe> element?

Embeds another webpage inside the current page.

<iframe src="https://example.com" width="600" height="400" title="Embedded Page"></iframe>

Q93. What is the sandbox attribute in iframes?

Restricts what the embedded content can do for security.

<iframe src="page.html" sandbox></iframe>

Restrictions include: no JavaScript, no form submission, no popups.


Q94. What is the <base> tag?

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 -->

Q95. What is the <address> tag?

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>

Q96. What is the <blockquote> tag?

Indicates a long quotation from another source.

<blockquote cite="https://example.com/">
  A really inspiring quote from somewhere.
</blockquote>

Q97. What is the <noscript> tag?

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>

Q98. What are global attributes?

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

30. HTML5 APIs

Q99. List the APIs available in HTML5

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

Q100. What is the WebSocket API?

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);
});

Q101. What is the Geolocation API?

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);
  });
}

31. Drag and Drop

Q102. Explain Drag and Drop in HTML5

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">

32. Geolocation API

Q103. How does the Geolocation API work?

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);
  }
);

33. Web Components

Q104. What are Web Components?

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>

34. HTML Entities & Encoding

Q105. What are HTML entities?

HTML entities are codes used to display reserved or special characters.

Character Entity
< &lt;
> &gt;
& &amp;
© &copy;
® &reg;
&trade;
@ &commat;
§ &sect;
(non-breaking space) &nbsp;
<p>5 &lt; 10 is true.</p>
<p>© 2026 My Company</p>

Q106. What is URL Encoding?

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

35. Deprecated Tags & Attributes

Q107. What HTML tags are deprecated in HTML5?

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

Q108. What is the <keygen> element?

The <keygen> element was used to generate encryption keys for forms. It's deprecated and should not be used.


Q109. What is Application Cache (AppCache)?

A deprecated HTML5 feature for offline web apps. Use Service Workers instead.

<!-- Deprecated approach -->
<html manifest="example.appcache">

Q110. Why use IndexedDB instead of WebSQL?

  • 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

36. Miscellaneous & Pro Tips

Q111. What is WHATWG?

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.


Q112. What is Modernizr?

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
}

Q113. What is CORS?

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.


Q114. Difference between progressive enhancement and graceful degradation?

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

Q115. What is the tabindex attribute?

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>

Q116. How to create a tooltip in HTML5?

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>

Q117. How to create a line break?

<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

Q120. How to ensure HTML5 app works offline?

Use:

  • Service Workers — Modern approach for offline caching.
  • Cache API — Store resources.
  • localStorage/sessionStorage — Store data.
  • IndexedDB — Large-scale storage.

🎯 Quick Revision Checklist

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
  • async vs defer in 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

🧠 Final Interview Revision Strategy

Before the interview, make sure you can explain the following without looking at notes:

Fundamentals

  • 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

Forms

  • Input types and validation
  • label, fieldset, legend, select, and datalist
  • GET vs POST
  • enctype and file uploads

Browser & Performance

  • DOM, CSSOM, render tree, layout, paint, and compositing
  • Critical Rendering Path
  • async vs defer
  • Image optimization and lazy loading
  • SSR vs CSR

Accessibility & SEO

  • Semantic HTML
  • alt text and form labels
  • Keyboard accessibility
  • ARIA and when to use it
  • Heading hierarchy
  • Metadata and structured data

Modern HTML & APIs

  • 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.


📚 References


🏆 Conclusion

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

About

A comprehensive, curated collection of essential HTML and HTML5 interview questions and answers, covering beginner to advanced concepts for web developers.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors