0% found this document useful (0 votes)
18 views15 pages

HTML Interview Questions & Answers Guide

The document provides a comprehensive set of HTML interview questions and answers, covering basic to advanced topics. Key concepts include the structure of HTML, semantic elements, accessibility practices, and security measures. It also discusses practical implementations such as forms, media embedding, and resource loading techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views15 pages

HTML Interview Questions & Answers Guide

The document provides a comprehensive set of HTML interview questions and answers, covering basic to advanced topics. Key concepts include the structure of HTML, semantic elements, accessibility practices, and security measures. It also discusses practical implementations such as forms, media embedding, and resource loading techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HTML Interview Q&A; — Part 1 (Basic & Intermediate)

1. What is HTML?
HTML (HyperText Markup Language) structures content on the web using elements (tags) that
describe meaning and layout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello HTML</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is HTML.</p>
</body>
</html>

2. What does the DOCTYPE do?


The DOCTYPE tells the browser which HTML standard to use. In HTML5, it enables standards
mode for consistent rendering.
<!DOCTYPE html>

3. Difference between block, inline, and inline-block elements?


Block elements start on a new line and take full width (e.g., <div>, <p>). Inline elements flow
with text and only take needed width (e.g., <span>, <a>). Inline-block flows inline but accepts
width/height.
<div style="background:#eee">block</div>
<span>inline</span>
<span style="display:inline-block;width:100px">inline-block</span>

4. What are semantic elements?


Semantic elements convey meaning to browsers and assistive tech (e.g., <header>, <main>,
<nav>, <section>, <article>, <aside>, <footer>). They improve SEO, accessibility, and
maintainability.
<header>
<nav>...</nav>
</header>
<main>
<article>
<h1>Post Title</h1>
<p>Content...</p>
</article>
<aside>Related links</aside>
</main>
<footer>&copy; 2025</footer>

5. Difference between <div> and <span>?


<div> is block-level (for layout/sections). <span> is inline (for small chunks of text). Both are
non-semantic containers.
<div class="card">
<h3>Profile</h3>
<p>Name: <span class="name">Ava</span></p>
</div>

6. What are attributes? Give examples.


Attributes add extra information to elements via name=value pairs, e.g., id, class, href, alt,
aria-*.
<a href="/about" target="_blank" rel="noopener">About</a>
<img src="[Link]" alt="Company logo" width="120" height="40">

7. What is the purpose of the <head> element?


<head> contains metadata and links not rendered as page content: <title>, meta, link, script,
etc.
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page</title>
<link rel="icon" href="/[Link]">
<link rel="stylesheet" href="/[Link]">
</head>

8. Explain the viewport meta tag.


It controls how a page is displayed on mobile devices. Without it, pages may appear
zoomed-out.
<meta name="viewport" content="width=device-width, initial-scale=1">
9. What are self-closing (void) elements?
Elements that cannot have children (e.g., <img>, <input>, <br>, <hr>, <meta>, <link>). In
HTML5 you don't need the trailing slash.
<img src="[Link]" alt="Cat">
<br>
<hr>

10. How to create links and set them to open in a new tab safely?
Use target="_blank" and rel="noopener" (and optionally rel="noreferrer") to prevent
[Link] security issues.
<a href="[Link] target="_blank" rel="noopener">Visit</a>

11. How to add images with accessible alt text?


Use meaningful alt describing purpose. If purely decorative, use empty alt (alt="").
<img src="[Link]" alt="Sales increased 25% from 2024 to 2025">

12. How to create lists (ul/ol) and definition lists (dl)?


Unordered lists use bullets (ul), ordered lists are numbered (ol), and definition lists pair terms
with descriptions (dl).
<ul>
<li>Apple</li><li>Banana</li><li>Cherry</li>
</ul>
<ol>
<li>Install</li><li>Configure</li><li>Run</li>
</ol>
<dl>
<dt>HTTP</dt><dd>Protocol for web data transfer</dd>
</dl>

13. Difference between id and class?


id is unique (one per page) and used for single elements or anchors. class can be reused for
styling and grouping.
<div id="hero" class="section hero-section"></div>

14. How to include external CSS and JS?


Use <link> for CSS in <head> and <script src> for JS. Prefer defer for scripts to avoid blocking
parsing.
<link rel="stylesheet" href="[Link]">
<script src="[Link]" defer></script>

15. What are data-* attributes?


Custom attributes to store extra info for scripts without polluting class names.
<button data-user-id="42" data-role="admin">Edit</button>
16. What are <strong> vs <b> and <em> vs <i>?
<strong> and <em> add semantic meaning (importance/emphasis) useful for accessibility. <b>
and <i> are purely presentational.
<p><strong>Warning:</strong> Low battery.</p>
<p><em>Really</em> important note.</p>
17. How to embed audio and video in HTML5?
Use <audio> and <video> with controls. Provide multiple sources and captions when possible.
<video controls width="480" poster="[Link]">
<source src="movie.mp4" type="video/mp4">
<track kind="captions" src="[Link]" srclang="en" label="English">
Sorry, your browser doesn't support HTML5 video.
</video>

18. What is the difference between <section> and <article>?


<article> is a self-contained composition (e.g., a blog post). <section> groups related content,
typically with a heading.
<section aria-labelledby="features-title">
<h2 id="features-title">Features</h2>
<article>
<h3>Offline Mode</h3>
<p>...</p>
</article>
</section>

19. Explain forms: labels, inputs, and accessibility.


Associate <label> with inputs using for/id or wrapping to improve usability and screen-reader
support.
<form>
<label for="email">Email</label>
<input id="email" type="email" required aria-describedby="emailHelp">
<small id="emailHelp">We'll never share your email.</small>
<button type="submit">Submit</button>
</form>

20. How to validate forms using HTML attributes?


Use type-specific inputs, required, minlength/maxlength, pattern, and constraint validation API.
<input type="password" required minlength="8" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
<!-- :invalid CSS can style invalid fields -->

21. What is the dialog element and how to use it?


<dialog> creates native modal/non-modal dialogs. Use showModal() in JS and provide a close
button.
<dialog id="dlg">
<p>Confirm action?</p>
<form method="dialog">
<button value="cancel">Cancel</button>
<button value="ok">OK</button>
</form>
</dialog>
<button onclick="[Link]('dlg').showModal()">Open</button>

22. Explain defer vs async on script tags.


async downloads and executes ASAP (order not guaranteed). defer downloads in parallel but
executes after parsing, in order.
<script src="[Link]" async></script>
<script src="[Link]" defer></script>

23. How to preload critical assets?


Use rel=preload for critical fonts, scripts, or images; preconnect for early TCP/TLS;
dns-prefetch for DNS hints.
<link rel="preconnect" href="[Link]
<link rel="dns-prefetch" href="//[Link]">
<link rel="preload" as="font" type="font/woff2" href="/fonts/Inter.woff2" crossorigin>

24. What is accessibility (a11y) and ARIA?


Accessibility makes content usable for people with disabilities. ARIA roles/props add semantics
when native HTML isn't enough.
<button aria-pressed="false" aria-label="Toggle mute">■</button>
25. What is the difference between src and href?
src replaces the element with the resource (e.g., <img src>), while href points to a resource for
navigation (e.g., <a href>).
<img src="[Link]" alt="...">
<a href="/docs">Docs</a>

26. How do iframes work and how to sandbox them?


iframes embed external pages. Use sandbox to restrict capabilities and allowlist only what's
needed.
<iframe src="[Link]
sandbox="allow-scripts allow-same-origin"
width="600" height="400" loading="lazy"></iframe>

27. How to lazy-load images and iframes?


Use loading="lazy" on <img> and <iframe> to defer loading offscreen content.
<img src="[Link]" alt="Hero" loading="lazy">
<iframe src="[Link]" loading="lazy"></iframe>

28. How to create responsive images (srcset, sizes)?


Use srcset with sizes so the browser picks the best image for the viewport.
<img
src="[Link]"
srcset="[Link] 400w, [Link] 800w, [Link] 1200w"
sizes="(max-width: 600px) 100vw, 600px"
alt="Mountains">
HTML Interview Q&A; — Part 2 (Advanced, Security &
Practical)
29. What is the picture element for art direction?
picture lets you switch images based on media conditions or formats (e.g., WebP fallback).
<picture>
<source srcset="[Link]" type="image/webp">
<source srcset="[Link]" type="image/jpeg">
<img src="[Link]" alt="Decorative">
</picture>

30. What are microdata and microformats? What about JSON-LD?


Microdata/microformats embed structured data in HTML. JSON-LD is the recommended way
to add [Link] data via a script tag.
<script type="application/ld+json">
{
"@context": "[Link]
"@type": "Article",
"headline": "HTML Interview",
"datePublished": "2025-08-25"
}
</script>

31. What is the DOM and how is it different from HTML source?
The DOM is a live tree representation used by the browser after parsing HTML; scripts can
mutate it at runtime.
<!-- HTML source -->
<ul id="list"></ul>
<script>
const ul = [Link]('list');
[Link]([Link]([Link]('li'), {textContent:'Item'}));
</script>

32. Explain Custom Elements and Shadow DOM.


Web Components allow reusable widgets. Custom elements define new tags; Shadow DOM
encapsulates structure and styles.
<template id="x-counter">
<style>
button{padding:.4rem}
</style>
<button part="btn">Count: <span id="v">0</span></button>
</template>
<script>
class XCounter extends HTMLElement{
#v=0;
constructor(){
super();
const root = [Link]({mode:'open'});
[Link]([Link]('x-counter').[Link](true));
[Link] = [Link]('button');
this.v = [Link]('#v');
[Link]('click',()=>{ [Link] = ++this.#v; });
}
}
[Link]('x-counter', XCounter);
</script>
<x-counter></x-counter>

33. How do templates and slots work?


<template> holds inert markup. <slot> lets parents project content into Shadow DOM.
<template id="tpl"><slot name="title"></slot><div><slot></slot></div></template>

34. What is progressive enhancement?


Start with semantic HTML, then add CSS/JS for richer UX so the core remains usable without
JS.
<button type="submit">Add to cart</button>
<script>/* enhance with fetch(), etc. */</script>

35. What is the Critical Rendering Path?


The sequence of steps the browser takes to paint pixels to the screen. Minimize
render-blocking resources to improve FCP/LCP.
<!-- Keep CSS small, mark non-critical as media=print or load async JS -->

36. How to use rel=preload vs rel=prefetch?


preload is for resources needed soon in the current navigation; prefetch is for future
navigations (lower priority).
<link rel="preload" as="image" href="/hero@[Link]">
<link rel="prefetch" href="/[Link]">

37. How to make tables accessible?


Use <caption>, <th scope>, headers/id for complex tables, and summary in nearby text.
<table>
<caption>Quarterly Revenue</caption>
<thead><tr><th scope="col">Q</th><th scope="col">Revenue</th></tr></thead>
<tbody><tr><th scope="row">Q1</th><td>$10k</td></tr></tbody>
</table>

38. Explain crossorigin and CORS with images, fonts, and fetches.
Use crossorigin on <img>/<link> when accessing cross-origin resources requiring credentials
or for canvas tainting rules.
<img src="[Link] crossorigin="anonymous" alt="...">
<link rel="stylesheet" href="[Link] crossorigin>
39. What are integrity (SRI) attributes?
Subresource Integrity allows the browser to verify files are not tampered with.
<script src="[Link]
integrity="sha384-BASE64HASH"
crossorigin="anonymous"></script>

40. How to embed SVG inline and manipulate it?


Inline SVG is part of the DOM; you can style via CSS and manipulate with JS.
<svg viewBox="0 0 100 10" width="200">
<rect width="100" height="10" fill="currentColor"/>
</svg>

41. Canvas vs SVG — when to use which?


Canvas is pixel-based and great for dynamic, large, frequently changing scenes; SVG is
vector-based and great for icons, charts with fewer elements.

42. What are meta charset and language declarations?


Use <meta charset="utf-8"> and lang attribute to aid parsing and accessibility.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"></head>

43. How to create anchor links and skip links for accessibility?
Use id targets and a visible focusable link early in the DOM to skip repetitive content.
<a class="skip-link" href="#main">Skip to content</a>
<main id="main">...</main>

44. What is contenteditable and designMode?


contenteditable makes an element editable; [Link]='on' toggles page-wide
editing (dev/debug use).
<div contenteditable="true">Edit me</div>

45. How do you handle internationalization (i18n) concerns in HTML?


Set lang, dir for RTL, use meta charset utf-8, and avoid hard-coding text in markup when
templating.
<html lang="ar" dir="rtl">...</html>

46. Common security issues and HTML's role in preventing XSS?


Never inject untrusted HTML. Prefer textContent, use CSP, sanitize input, and encode output.
Use rel=noopener on _blank.
<!-- Example: escape user content -->
<div id="out"></div>
<script>
const user = '<img src=x onerror=alert(1)>';
[Link]('out').textContent = user; // safe
</script>

47. What is Content Security Policy (CSP)?


CSP is a response header (or meta) that restricts sources of scripts/styles/images to mitigate
XSS and data injection.
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' https: da

48. How to prevent clickjacking?


Set X-Frame-Options or frame-ancestors via CSP to control framing; use same-origin checks
in framed apps.
<!-- Response header example -->
Content-Security-Policy: frame-ancestors 'self' [Link]
49. Secure form submissions over HTTPS and with autocomplete hints.
Always use HTTPS, set autocomplete attributes appropriately, and use type=password, email,
etc.
<form action="[Link] method="post" autocomplete="on">
<input type="email" name="email" autocomplete="email" required>
<input type="password" name="password" autocomplete="current-password" required>
</form>

50. How to use the download attribute on links?


download hints that the target should be downloaded rather than navigated to, optionally with a
filename.
<a href="/files/[Link]" download="[Link]">Download CSV</a>

51. How to build a simple accessible nav menu?


Use <nav>, proper list markup, visible focus states, and aria-current on the active link.
<nav aria-label="Primary">
<ul>
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/blog">Blog</a></li>
</ul>
</nav>

52. How to create a favicon and touch icons?


Use <link rel="icon"> for favicon and various sizes for touch icons. Keep ICO/PNG/WebP
variants.
<link rel="icon" href="/[Link]" sizes="any">
<link rel="icon" href="/[Link]" type="image/svg+xml">
<link rel="apple-touch-icon" href="/[Link]">

53. What is the purpose of rel=noopener, noreferrer, ugc, sponsored on


links?
They control referrer behavior and declare link relationship for security/SEO (ugc/sponsored).
<a href="[Link] target="_blank" rel="noopener noreferrer">External</a>

54. Explain form enctype values.


application/x-www-form-urlencoded (default), multipart/form-data (file uploads), text/plain
(debug).
<form method="post" enctype="multipart/form-data">
<input type="file" name="avatar">
</form>
HTML Interview — Part 3 (Scenario-Based + Quick
Revision Table)
Scenario-Based Questions
1. Page has massive images and poor performance.
Use responsive images (srcset/sizes), WebP/AVIF, width/height to avoid layout shift,
lazy-loading, and preloading hero images.
<img src="[Link]"
srcset="[Link] 600w, [Link] 900w, [Link] 1200w"
sizes="(max-width: 700px) 100vw, 700px"
width="700" height="350" loading="lazy" alt="Hero">

2. Make complex form accessible.


Use <label>, aria-describedby for help text, fieldset/legend for grouping, and proper input types
and constraints.
<fieldset>
<legend>Contact</legend>
<label for="tel">Phone</label>
<input id="tel" type="tel" aria-describedby="tel-hint">
<small id="tel-hint">Include country code.</small>
</fieldset>

3. Embed third-party widget safely.


Use <iframe sandbox> with only needed allowances; use allow attribute for features (camera,
geolocation).
<iframe src='[Link] sandbox='allow-scripts' allow='geolocation'></iframe>

4. Need printable page without JS.


Use semantic HTML and print styles; avoid JS-only content.
<link rel="stylesheet" href="[Link]" media="print">
5. Provide dark mode
Use prefers-color-scheme to auto-switch and offer a toggle persisted in localStorage.
<meta name="color-scheme" content="light dark">
<link rel="stylesheet" href="[Link]">

6. Avoid CLS on images


Always set width/height or aspect-ratio so space is reserved before image loads.
<img src="[Link]" alt="..." width="800" height="450">

7. Inline critical CSS and defer rest


Inline minimal critical CSS in head; load rest async to speed up first paint.
<link rel="preload" as="style" href="[Link]" onload="[Link]='stylesheet'">

8. Make a11y-friendly modal


Prefer <dialog>. Focus trap and aria-modal for custom modals; return focus to opener.
<dialog id="m"></dialog>
9. SEO-rich article page
Use semantic tags, h1-h6 hierarchy, meta description, Open Graph/Twitter tags, and JSON-LD
schema.
<meta name="description" content="...">
<meta property="og:title" content="...">

10. Offline-capable shell


Use Service Worker (beyond HTML) but keep HTML resilient with cache-first shell and noscript
fallbacks.
<noscript>Please enable JavaScript for full experience.</noscript>

Quick Revision Table


Topic Snippet / Reminder
Doctype <!DOCTYPE html>
Meta charset <meta charset="utf-8">
Viewport <meta name="viewport" content="width=device-width, initial-scale=1">
Link CSS <link rel="stylesheet" href="[Link]">
Defer script <script src="[Link]" defer></script>
Async script <script src="[Link]" async></script>
Lazy image <img loading="lazy" ...>
Responsive image srcset + sizes
External link (safe) target="_blank" rel="noopener"
Dialog <dialog>
Accessible label <label for=...> + id
Skip link <a href="#main">Skip to content</a>
Favicon <link rel="icon" href="/[Link]">
Preconnect <link rel="preconnect" href="[Link]
Preload <link rel="preload" as="...">
CSP (meta) <meta http-equiv='Content-Security-Policy' ...>
Sandbox iframe sandbox='...' allow='...'
SRI integrity='...' crossorigin='anonymous'
JSON-LD <script type="application/ld+json">...</script>
ARIA pressed button aria-pressed="true|false"

You might also like