HTML/HTML5 Complete Interview Guide
Table of Contentsโ
- Introduction
- HTML Fundamentals
- HTML5 New Features
- Semantic HTML
- Forms and Input
- Multimedia Elements
- HTML5 Storage
- Meta Tags and SEO
- Accessibility
- HTML Best Practices
- Performance Optimization
- Common Interview Questions
- Coding Challenges
- Advanced Topics
Introductionโ
HTML (HyperText Markup Language) is the standard markup language for creating web pages. HTML5 is the fifth and current major version of HTML, introducing numerous new features, semantic elements, and APIs that have transformed web development.
This guide covers everything you need to know about HTML/HTML5 from an interview perspective, including fundamental concepts, new features, best practices, and common interview questions.
HTML Fundamentalsโ
What is HTML?โ
HTML is a markup language that defines the structure and content of web pages. It uses a system of tags to describe different types of content and their relationships. Browsers parse HTML to render web pages.
Key characteristics:
- Markup language, not a programming language
- Uses tags enclosed in angle brackets (
<tag>) - Case-insensitive (but lowercase is convention)
- Consists of elements, attributes, and content
- Forms the structural layer of web pages
HTML Document Structureโ
Every HTML document follows a basic structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
Components:
<!DOCTYPE html>: Declares document type and HTML version<html>: Root element containing all content<head>: Contains metadata, links to resources, and scripts<body>: Contains visible page content
DOCTYPE Declarationโ
The DOCTYPE declaration tells the browser which version of HTML the page uses and triggers standards mode rendering.
HTML5 DOCTYPE:
<!DOCTYPE html>
Why it matters:
- Ensures consistent rendering across browsers
- Triggers standards mode vs quirks mode
- HTML5 simplified from previous verbose declarations
- Must be the very first thing in an HTML document
Previous DOCTYPE examples:
<!-- HTML 4.01 Strict -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<!-- XHTML 1.0 Strict -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
HTML Elements and Tagsโ
Elements: Complete HTML structures including opening tag, content, and closing tag Tags: Markers that define element boundaries
Types of elements:
Paired tags:
<p>This is a paragraph</p>
<div>This is a division</div>
Self-closing/Void tags:
<img src="image.jpg" alt="Description">
<br>
<hr>
<input type="text">
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
Block-level elements:
- Take up full width available
- Start on new line
- Examples:
<div>,<p>,<h1>-<h6>,<section>,<article>
Inline elements:
- Take up only necessary width
- Don't start new line
- Examples:
<span>,<a>,<strong>,<em>,<img>
Attributesโ
Attributes provide additional information about elements and modify their behavior or appearance.
Syntax:
<element attribute="value">Content</element>
Common global attributes:
id: Unique identifier for elementclass: One or more class names for styling/scriptingstyle: Inline CSS stylestitle: Advisory information (tooltip)data-*: Custom data attributeshidden: Hides element from displaytabindex: Controls keyboard navigation ordercontenteditable: Makes element editabledraggable: Makes element draggable
Boolean attributes:
<input type="checkbox" checked>
<button disabled>Click me</button>
<script async src="script.js"></script>
HTML5 New Featuresโ
Key Improvementsโ
HTML5 introduced significant improvements over HTML4:
- Simplified syntax - Cleaner DOCTYPE, character set declaration
- New semantic elements - Better document structure
- Multimedia support - Native audio and video
- Graphics capabilities - Canvas and SVG
- Enhanced forms - New input types and validation
- Web APIs - Geolocation, Web Storage, Web Workers
- Improved parsing - Better error handling
- Offline capabilities - Application cache, service workers
- Mobile-friendly - Better support for mobile devices
New Semantic Elementsโ
HTML5 introduced semantic elements that clearly describe their meaning:
<header> <!-- Header content -->
<nav> <!-- Navigation links -->
<main> <!-- Main content -->
<article> <!-- Independent, self-contained content -->
<section> <!-- Thematic grouping of content -->
<aside> <!-- Content aside from main content -->
<footer> <!-- Footer content -->
<figure> <!-- Self-contained content like images -->
<figcaption> <!-- Caption for figure -->
<mark> <!-- Highlighted/marked text -->
<time> <!-- Date/time -->
<details> <!-- Additional details user can show/hide -->
<summary> <!-- Heading for details element -->
Example structure:
<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
</nav>
</header>
<main>
<article>
<header>
<h1>Article Title</h1>
<time datetime="2024-01-15">January 15, 2024</time>
</header>
<section>
<h2>Section Heading</h2>
<p>Content here...</p>
</section>
</article>
<aside>
<h3>Related Links</h3>
</aside>
</main>
<footer>
<p>© 2024 Company Name</p>
</footer>
New Form Elementsโ
Datalist: Provides autocomplete suggestions for input fields.
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
</datalist>
Output: Displays calculation results.
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" id="a" value="50"> +
<input type="number" id="b" value="50"> =
<output name="result" for="a b">100</output>
</form>
Progress: Shows task completion progress.
<progress value="70" max="100">70%</progress>
Meter: Shows scalar measurement within a range.
<meter value="6" min="0" max="10" low="3" high="7" optimum="5">6 out of 10</meter>
New Input Typesโ
HTML5 introduced many new input types with built-in validation:
<!-- Email with validation -->
<input type="email" required>
<!-- URL with validation -->
<input type="url" placeholder="https://example.com">
<!-- Number with min/max -->
<input type="number" min="1" max="100" step="1">
<!-- Range slider -->
<input type="range" min="0" max="100" value="50">
<!-- Date picker -->
<input type="date">
<!-- Time picker -->
<input type="time">
<!-- Date and time -->
<input type="datetime-local">
<!-- Month picker -->
<input type="month">
<!-- Week picker -->
<input type="week">
<!-- Color picker -->
<input type="color" value="#ff0000">
<!-- Telephone -->
<input type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
<!-- Search box -->
<input type="search" placeholder="Search...">
New APIsโ
HTML5 introduced powerful JavaScript APIs:
Geolocation API:
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
}
);
Drag and Drop API:
<div draggable="true" ondragstart="drag(event)">Drag me</div>
<div ondrop="drop(event)" ondragover="allowDrop(event)">Drop here</div>
Web Workers: Run scripts in background threads without blocking UI.
WebSocket API: Full-duplex communication channels over single TCP connection.
Canvas API: Draw graphics programmatically using JavaScript.
History API: Manipulate browser history for single-page applications.
Semantic HTMLโ
Why Semantics Matterโ
Using semantic HTML provides multiple benefits:
- Accessibility - Screen readers understand content structure
- SEO - Search engines better understand content importance
- Maintainability - Code is more readable and self-documenting
- Consistency - Standard elements ensure consistent behavior
- Future-proofing - Semantic markup adapts better to new devices
Semantic vs Non-Semantic Elementsโ
Semantic elements:
<header>, <nav>, <main>, <article>, <section>, <aside>, <footer>
<h1>-<h6>, <p>, <figure>, <figcaption>, <mark>, <time>
Non-semantic elements:
<div>, <span>
Bad practice (non-semantic):
<div class="header">
<div class="nav">
<div class="nav-item">Home</div>
</div>
</div>
<div class="content">
<div class="article">
<div class="title">Article Title</div>
<div class="body">Content...</div>
</div>
</div>
Good practice (semantic):
<header>
<nav>
<a href="#home">Home</a>
</nav>
</header>
<main>
<article>
<h1>Article Title</h1>
<p>Content...</p>
</article>
</main>
Document Outlineโ
HTML5 introduced the concept of document outline where each sectioning element (<article>, <section>, <nav>, <aside>) creates a new section in the outline.
Proper heading hierarchy:
<h1>Main Title</h1>
<section>
<h2>Section Title</h2>
<h3>Subsection Title</h3>
</section>
<section>
<h2>Another Section</h2>
</section>
Common mistake - skipping levels:
<!-- Bad: Skipping from h1 to h3 -->
<h1>Title</h1>
<h3>Subtitle</h3>
<!-- Good: Sequential hierarchy -->
<h1>Title</h1>
<h2>Subtitle</h2>
Forms and Inputโ
Form Elementsโ
Basic form structure:
<form action="/submit" method="POST" enctype="multipart/form-data">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select...</option>
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
</select>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio" rows="4"></textarea>
<fieldset>
<legend>Preferences</legend>
<label>
<input type="checkbox" name="newsletter" value="yes">
Subscribe to newsletter
</label>
</fieldset>
<button type="submit">Submit</button>
</form>
Form attributes:
action: URL where form data is sentmethod: HTTP method (GET or POST)enctype: How form data is encodedapplication/x-www-form-urlencoded(default)multipart/form-data(for file uploads)text/plain
autocomplete: Enable/disable autocompletenovalidate: Disable HTML5 validationtarget: Where to display response (_blank, _self, _parent, _top)
Form Validationโ
HTML5 built-in validation attributes:
<!-- Required field -->
<input type="text" required>
<!-- Pattern matching -->
<input type="text" pattern="[A-Za-z]{3,}" title="At least 3 letters">
<!-- Min/Max length -->
<input type="text" minlength="3" maxlength="20">
<!-- Min/Max value -->
<input type="number" min="1" max="100">
<!-- Multiple values (email) -->
<input type="email" multiple>
<!-- Custom validation message -->
<input type="email" required
oninvalid="this.setCustomValidity('Please enter valid email')"
oninput="this.setCustomValidity('')">
Validation pseudo-classes:
input:valid {
border-color: green;
}
input:invalid {
border-color: red;
}
input:required {
border-left: 3px solid blue;
}
input:optional {
border-left: 3px solid gray;
}
JavaScript validation API:
const input = document.querySelector('input');
// Check validity
if (input.checkValidity()) {
console.log('Valid');
} else {
console.log(input.validationMessage);
}
// Custom validation
input.setCustomValidity('This field must contain X');
// Clear custom validation
input.setCustomValidity('');
Form Attributesโ
Input attributes:
<!-- Autofocus on page load -->
<input type="text" autofocus>
<!-- Placeholder text -->
<input type="text" placeholder="Enter name...">
<!-- Readonly (can be focused, submitted) -->
<input type="text" value="Cannot edit" readonly>
<!-- Disabled (cannot be focused, not submitted) -->
<input type="text" disabled>
<!-- Autocomplete -->
<input type="email" autocomplete="email">
<!-- Input mode for virtual keyboards -->
<input type="text" inputmode="numeric">
<!-- List for autocomplete -->
<input type="text" list="suggestions">
<!-- Multiple file upload -->
<input type="file" multiple accept="image/*">
Multimedia Elementsโ
Audio and Videoโ
Video element:
<video width="640" height="360" controls poster="thumbnail.jpg">
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="English">
Your browser doesn't support video.
</video>
Video attributes:
controls: Show playback controlsautoplay: Start playing automaticallyloop: Loop playbackmuted: Mute audio by defaultpreload: How to preload (none, metadata, auto)poster: Image shown before playback
Audio element:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Your browser doesn't support audio.
</audio>
JavaScript media API:
const video = document.querySelector('video');
video.play();
video.pause();
video.currentTime = 10; // Skip to 10 seconds
video.volume = 0.5; // 50% volume
video.playbackRate = 1.5; // 1.5x speed
// Event listeners
video.addEventListener('play', () => console.log('Playing'));
video.addEventListener('ended', () => console.log('Finished'));
Canvasโ
Canvas allows drawing graphics via JavaScript:
<canvas id="myCanvas" width="500" height="400"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 150, 100);
// Draw circle
ctx.beginPath();
ctx.arc(300, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
// Draw text
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 100, 250);
// Draw line
ctx.beginPath();
ctx.moveTo(50, 300);
ctx.lineTo(450, 350);
ctx.strokeStyle = 'green';
ctx.lineWidth = 5;
ctx.stroke();
</script>
SVGโ
SVG (Scalable Vector Graphics) can be embedded directly in HTML5:
<svg width="200" height="200">
<circle cx="100" cy="100" r="80" fill="blue" />
<rect x="50" y="50" width="100" height="100" fill="red" opacity="0.5" />
<line x1="0" y1="0" x2="200" y2="200" stroke="green" stroke-width="2" />
<text x="100" y="100" text-anchor="middle" fill="white">SVG Text</text>
</svg>
Canvas vs SVG:
- Canvas: Raster-based, pixel manipulation, better for many objects, games
- SVG: Vector-based, scalable, DOM-based, better for interactive graphics
HTML5 Storageโ
localStorage vs sessionStorageโ
Both provide client-side storage with simple key-value API:
localStorage:
- Persists until explicitly cleared
- Shared across all tabs/windows of same origin
- Typical limit: 5-10MB
sessionStorage:
- Persists only for page session
- Separate for each tab/window
- Cleared when tab/window closes
API (identical for both):
// Store data
localStorage.setItem('username', 'john');
localStorage.setItem('user', JSON.stringify({name: 'John', age: 30}));
// Retrieve data
const username = localStorage.getItem('username');
const user = JSON.parse(localStorage.getItem('user'));
// Remove item
localStorage.removeItem('username');
// Clear all
localStorage.clear();
// Get number of items
console.log(localStorage.length);
// Get key by index
const key = localStorage.key(0);
// Using property access (not recommended)
localStorage.username = 'john';
console.log(localStorage.username);
Storage event:
// Listen for storage changes (in other tabs)
window.addEventListener('storage', (e) => {
console.log('Key:', e.key);
console.log('Old value:', e.oldValue);
console.log('New value:', e.newValue);
console.log('URL:', e.url);
});
Cookies vs Web Storageโ
Cookies:
- Sent with every HTTP request (increases overhead)
- 4KB limit per cookie
- Can set expiration date
- Can be HTTP-only (not accessible via JavaScript)
- Can be Secure (HTTPS only)
Web Storage:
- Not sent with requests
- 5-10MB storage limit
- Only accessible via JavaScript
- Simpler API
- No expiration (localStorage) or session-based (sessionStorage)
When to use cookies:
- Server needs the data
- Need expiration control
- Need secure/HTTP-only flags
When to use Web Storage:
- Client-side only data
- Larger storage needs
- Better performance (no network overhead)
IndexedDBโ
IndexedDB is a low-level API for storing significant amounts of structured data:
// Open database
const request = indexedDB.open('MyDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create object store
const objectStore = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true });
// Create indexes
objectStore.createIndex('email', 'email', { unique: true });
objectStore.createIndex('name', 'name', { unique: false });
};
request.onsuccess = (event) => {
const db = event.target.result;
// Add data
const transaction = db.transaction(['users'], 'readwrite');
const objectStore = transaction.objectStore('users');
objectStore.add({ name: 'John', email: 'john@example.com' });
// Read data
const getRequest = objectStore.get(1);
getRequest.onsuccess = () => {
console.log(getRequest.result);
};
};
Meta Tags and SEOโ
Essential Meta Tagsโ
<head>
<!-- Character encoding -->
<meta charset="UTF-8">
<!-- Viewport for responsive design -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Page description for search engines -->
<meta name="description" content="Brief page description (150-160 chars)">
<!-- Keywords (less important now) -->
<meta name="keywords" content="keyword1, keyword2, keyword3">
<!-- Author -->
<meta name="author" content="Author Name">
<!-- Robots directives -->
<meta name="robots" content="index, follow">
<!-- Canonical URL -->
<link rel="canonical" href="https://example.com/page">
<!-- Language -->
<html lang="en">
<!-- Theme color for mobile browsers -->
<meta name="theme-color" content="#4285f4">
<!-- Favicon -->
<link rel="icon" type="image/png" href="/favicon.png">
<!-- Apple touch icon -->
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>
Open Graph and Twitter Cardsโ
Open Graph (Facebook, LinkedIn):
<meta property="og:title" content="Page Title">
<meta property="og:description" content="Page description">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:url" content="https://example.com/page">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Site Name">
Twitter Cards:
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@username">
<meta name="twitter:title" content="Page Title">
<meta name="twitter:description" content="Page description">
<meta name="twitter:image" content="https://example.com/image.jpg">
Accessibilityโ
ARIA Attributesโ
ARIA (Accessible Rich Internet Applications) provides additional semantics for assistive technologies:
ARIA roles:
<div role="navigation">Navigation content</div>
<div role="main">Main content</div>
<div role="complementary">Sidebar content</div>
<button role="button" aria-pressed="false">Toggle</button>
<div role="alert">Important message</div>
ARIA states and properties:
<!-- Labeling -->
<button aria-label="Close dialog">X</button>
<div aria-labelledby="section-heading">
<h2 id="section-heading">Section Title</h2>
</div>
<!-- Descriptions -->
<input type="text" aria-describedby="name-help">
<span id="name-help">Enter your full name</span>
<!-- States -->
<button aria-pressed="true">Active</button>
<div aria-expanded="false">Collapsed content</div>
<input type="checkbox" aria-checked="true">
<button aria-disabled="true">Disabled</button>
<!-- Live regions -->
<div aria-live="polite">Updates announced politely</div>
<div aria-live="assertive">Urgent updates</div>
<!-- Hidden content -->
<div aria-hidden="true">Hidden from screen readers</div>
Accessibility Best Practicesโ
Semantic HTML: Use appropriate elements instead of generic divs/spans with ARIA.
Keyboard navigation:
<!-- All interactive elements should be keyboard accessible -->
<button tabindex="0">Clickable</button>
<div tabindex="-1">Programmatically focusable</div>
Alt text for images:
<!-- Descriptive alt text -->
<img src="chart.png" alt="Sales increased 25% in Q4">
<!-- Decorative images -->
<img src="decorative.png" alt="">
Form labels:
<!-- Always associate labels with inputs -->
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<!-- Or wrap input -->
<label>
Email:
<input type="email" name="email">
</label>
Focus indicators:
/* Never remove focus outlines without replacement */
button:focus {
outline: 2px solid blue;
outline-offset: 2px;
}
Color contrast: Ensure sufficient contrast ratio (WCAG guidelines):
- Normal text: 4.5:1 minimum
- Large text: 3:1 minimum
Skip links:
<a href="#main-content" class="skip-link">Skip to main content</a>
<main id="main-content">
<!-- Content -->
</main>
HTML Best Practicesโ
- Use semantic elements - Choose appropriate HTML5 semantic tags
- Valid HTML - Write valid, well-formed HTML
- Proper nesting - Close tags in correct order
- Lowercase tags and attributes - Use lowercase for consistency
- Quote attribute values - Always quote attribute values
- Include alt text - All images should have meaningful alt attributes
- Use relative URLs - When possible, for easier maintenance
- Separate concerns - Keep HTML, CSS, and JavaScript separate
- Minimize inline styles - Use external stylesheets
- Accessibility first - Consider accessibility from the start
- Mobile-first - Design for mobile, enhance for desktop
- Validate markup - Use W3C validator to check HTML
- Use comments wisely - Comment complex structures, not obvious code
- Consistent indentation - Use 2 or 4 spaces consistently
- One h1 per page - Use single main heading for SEO
Performance Optimizationโ
Minimize DOM size:
- Keep DOM depth under 32 levels
- Avoid more than 60 children per parent
- Limit total DOM nodes to under 1500
Optimize images:
<!-- Responsive images -->
<img srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, 800px"
src="medium.jpg" alt="Description">
<!-- Lazy loading -->
<img src="image.jpg" loading="lazy" alt="Description">
<!-- Modern formats with fallback -->
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="Description">
</picture>
Preload critical resources:
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preconnect" href="https://cdn.example.com">
<link rel="dns-prefetch" href="https://analytics.example.com">
Defer non-critical resources:
<script src="script.js" defer></script>
<script src="analytics.js" async></script>
Minimize HTTP requests:
- Combine files where appropriate
- Use CSS sprites for small images
- Inline critical CSS
- Remove unused code
Common Interview Questionsโ
Q1: What's the difference between HTML and HTML5?โ
HTML5 is the latest version with new features:
- New semantic elements (header, nav, article, section, footer)
- Audio and video support without plugins
- Canvas and SVG for graphics
- New form input types and validation
- Web Storage (localStorage, sessionStorage)
- New APIs (Geolocation, Web Workers, WebSocket)
- Improved accessibility and SEO
- Better mobile support
Q2: What's the difference between <div> and <span>?โ
<div>is block-level: takes full width, starts on new line<span>is inline: takes only necessary width, doesn't break line- Both are non-semantic containers
- Use semantic alternatives when possible
Q3: What's the difference between id and class?โ
id: Unique identifier, one per page, higher CSS specificityclass: Reusable identifier, multiple per element, lower specificityidcan be used for fragment identifiers in URLs (#section)classbetter for styling multiple elements
Q4: What are data attributes?โ
Custom attributes starting with data- for storing custom data:
<div data-user-id="123" data-role="admin">User Info</div>
const element = document.querySelector('div');
console.log(element.dataset.userId); // "123"
console.log(element.dataset.role); // "admin"
element.dataset.status = 'active'; // Sets data-status="active"
Q5: Explain semantic HTML and its benefitsโ
Semantic HTML uses elements that clearly describe their meaning:
- Better accessibility for screen readers
- Improved SEO as search engines understand content
- More maintainable code
- Consistent behavior across browsers
- Examples:
<header>,<nav>,<article>,<aside>,<footer>
Q6: What's the difference between localStorage and sessionStorage?โ
- localStorage: Persists until explicitly deleted, shared across tabs
- sessionStorage: Cleared when tab closes, isolated per tab
- Both have same API and 5-10MB storage limit
- Both store string data only (use JSON for objects)