00 · Orientation
Welcome! This course is a single‑file interactive textbook built for clarity and depth. Each module includes annotated examples, gotchas, checklists, and an embedded code runner.
- HTML anatomy, semantics, and document structure
- Forms, tables, media, and accessibility
- SEO meta, performance, and best practices
None. You only need a browser. Use the runner below to test snippets instantly.
- Skim theory → run code → take quiz
- Build your own examples
- Read the checklists before shipping
01 · What is HTML?
Theory: HTML (HyperText Markup Language) is the standard language for creating web pages. It describes the structure and content of a webpage using elements called "tags". HTML tells the browser what content to display and how it's organized — headings, paragraphs, links, images, lists, and more.
HTML uses tags surrounded by angle brackets < and >. Most tags come in pairs: an opening tag and a closing tag. The content goes between these tags.
- Elements: Building blocks of HTML (like
<p>,<h1>,<div>) - Tags: The syntax that defines elements (opening and closing)
- Attributes: Extra information about elements (like
href,src,alt) - Structure: HTML documents have a hierarchical tree structure
Example Here's a complete HTML document structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Web Page</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is my first web page built with HTML.</p>
<p>HTML is the foundation of every website you visit.</p>
</body>
</html>
💡 Understanding the structure
<!DOCTYPE html>— Tells the browser this is an HTML5 document<html>— The root element that contains all other elements<head>— Contains metadata (information about the page)<meta charset="UTF-8">— Defines character encoding for proper text display<title>— Text shown in browser tab<body>— Contains all visible content<h1>— Main heading<p>— Paragraph text
🎯 Why Learn HTML?
- Foundation of all websites — every site uses HTML
- Easy to learn — you can start building in minutes
- Works everywhere — all browsers support HTML
- Essential skill — needed for web development careers
- Free and open — no licenses or fees required
02 · Syntax & Anatomy
HTML is made of elements written as <tags> with optional attributes. Most elements have an opening tag, content, and a closing tag.
<p title="tooltip">Hello <strong>HTML</strong>!</p>
<!-- Opening tag --> <p title="tooltip">
<!-- Content --> Hello <strong>HTML</strong>!
<!-- Closing tag --> </p>
Void elements (no closing tag)
Examples: <br>, <img>, <hr>, <meta>, <link>, <input>. They must not have closing tags or children.
Global attributes you should know
id,class,style,title,hidden,tabindex,lang,dir- ARIA:
role,aria-label,aria-live,aria-expanded…
03 · Headings & Paragraphs
Theory: Headings define titles and structure your content into sections. Paragraphs contain blocks of text. There are six levels of headings in HTML, from <h1> (most important) to <h6> (least important).
Headings Use headings to create a logical outline:
<h1>— Main page title (use only once per page)<h2>— Major sections<h3>— Subsections<h4>to<h6>— Further subdivisions
<h1>Website Main Title</h1>
<h2>Section 1: Introduction</h2>
<p>This is a paragraph with introductory text.</p>
<h3>Subsection 1.1</h3>
<p>More detailed information here.</p>
<h2>Section 2: Getting Started</h2>
<p>Another section with its own content.</p>
⚠️ Important Rules for Headings
- Only one
<h1>per page — It represents the main topic and is crucial for SEO - Don't skip levels — Go from h2 to h3, not h2 to h4
- Don't use headings for styling — Use CSS if you want big/bold text
- Maintain hierarchy — Headings should follow a logical order
- Screen readers use headings — They help users navigate your page
- Keep paragraphs focused — one idea per paragraph
- Don't use
<br>for spacing — use CSS margins instead - Use semantic elements inside paragraphs:
<strong>,<em>,<a>
<!-- Good Example -->
<article>
<h1>How to Learn HTML</h1>
<p>HTML is the foundation of web development.
Start with the basics and practice regularly.</p>
<h2>Step 1: Learn the Syntax</h2>
<p>Understanding tags and elements is your first step.</p>
<h2>Step 2: Build Projects</h2>
<p>Practice by creating real websites.</p>
</article>
<!-- Bad Example -->
<h1>Title</h1>
<h4>Skipped h2 and h3 - confusing!</h4>
<h1>Multiple h1 tags - bad for SEO!</h1>
04 · Text & Inline Elements
Semantics Use <em> for emphasis and <strong> for importance (not as styling). Prefer <abbr> for acronyms, <mark> to highlight, and <code> for inline code.
- Headings:
<h1>…<h6>(one logical outline) - Paragraph:
<p>; Quotes:<blockquote>and<q> - Inline:
<span>,<a>,<strong>,<em>,<small>,<sup>,<sub>
<h1>Article Title</h1>
<p>HTML gives text structure. Use <strong>importance</strong> and <em>emphasis</em> consciously.</p>
<p>Quote:</p>
<blockquote cite="https://html.spec.whatwg.org">The standard defines the web.</blockquote>
05 · Links & Images
Links connect pages and resources. The <a> (anchor) element creates clickable links.
<!-- External link -->
<a href="https://example.com">Visit Example</a>
<!-- Open in new tab -->
<a href="https://example.com" target="_blank">
Visit Example
</a>
<!-- Link to another page -->
<a href="about.html">About Us</a>
<!-- Link to email -->
<a href="mailto:hello@example.com">Email Us</a>
<!-- Link to phone -->
<a href="tel:+1234567890">Call Us</a>
Images make pages visual. Always include alt text for accessibility.
<!-- Basic image -->
<img src="logo.png" alt="Company logo">
<!-- Image with dimensions -->
<img src="profile.jpg"
alt="My profile photo"
width="200"
height="200">
<!-- Clickable image -->
<a href="gallery.html">
<img src="thumbnail.jpg" alt="Gallery preview">
</a>
The alt attribute:
- Describes the image for screen readers (accessibility)
- Shows text if image fails to load
- Helps search engines understand your images (SEO)
- Should be descriptive and meaningful
<!-- Good ALT text -->
<img src="sunset.jpg" alt="Orange sunset over mountain lake">
<!-- Bad ALT text -->
<img src="sunset.jpg" alt="image123"> <!-- Not descriptive -->
<img src="sunset.jpg" alt=""> <!-- Missing description -->
🔗 Link Best Practices
- Use descriptive text — Not "click here", but "Read our privacy policy"
- Add
target="_blank"for external sites to open in new tab - Use relative paths for internal links:
href="about.html" - Add
rel="noopener"when usingtarget="_blank"for security
🖼️ Image File Types
- JPG/JPEG — Photos, complex images (compressed, smaller files)
- PNG — Graphics, logos, images with transparency
- GIF — Simple animations
- SVG — Logos, icons (scalable, never pixelated)
- WebP/AVIF — Modern formats (better compression, smaller files)
06 · Lists (Basic)
Theory: Lists organize related items. HTML has three types: unordered (bullets), ordered (numbers), and definition lists.
Unordered List Use <ul> for bullet points:
<h3>Shopping List</h3>
<ul>
<li>Bread</li>
<li>Milk</li>
<li>Eggs</li>
<li>Cheese</li>
</ul>
Ordered List Use <ol> for numbered steps:
<h3>Recipe Steps</h3>
<ol>
<li>Preheat oven to 350°F</li>
<li>Mix ingredients</li>
<li>Pour into pan</li>
<li>Bake for 25 minutes</li>
</ol>
Nested Lists You can put lists inside lists:
<h3>Web Development Skills</h3>
<ul>
<li>Frontend
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</li>
<li>Backend
<ul>
<li>Node.js</li>
<li>Python</li>
<li>PHP</li>
</ul>
</li>
</ul>
💡 When to use each list type
- Unordered (
<ul>) — When order doesn't matter (ingredients, features) - Ordered (
<ol>) — When order is important (instructions, rankings) - Definition (
<dl>) — For term-definition pairs (glossaries, FAQs)
07 · Structure & Semantics
Use semantic layout for meaning and accessibility.
<header>Site header</header>
<nav aria-label="Primary">…</nav>
<main id="main">
<article>
<h1>Post</h1>
<section>…</section>
<aside>Related</aside>
</article>
</main>
<footer>Copyright</footer>
- Prefer
<button>over clickable<div>. - One
<h1>per page/sectioning root is fine; maintain a logical hierarchy.
08 · Div & Span
Theory: <div> and <span> are generic containers with no semantic meaning. Use them when no semantic element fits, primarily for styling with CSS or manipulating with JavaScript.
DIV - Block Container
- Takes full width available
- Starts on a new line
- Used to group block-level content
- Common for layout structure
<div class="container">
<div class="header">
<h1>My Website</h1>
</div>
<div class="content">
<p>Main content here</p>
</div>
</div>
SPAN - Inline Container
- Takes only needed width
- Stays on the same line
- Used to style parts of text
- Doesn't break flow
<p>This is a
<span style="color: red;">red</span>
word in a sentence.
</p>
<p>Price:
<span class="price">$99.99</span>
</p>
- Use
<header>,<nav>,<main>,<footer>instead of<div>for page structure - Use
<strong>,<em>,<mark>instead of<span>for semantic emphasis - Use
<button>instead of<div>for clickable elements
<!-- Bad: Using div for everything -->
<div class="button" onclick="...">Click Me</div>
<!-- Good: Using semantic button -->
<button onclick="...">Click Me</button>
<!-- Bad: Using span for emphasis -->
<span style="font-weight:bold">Important</span>
<!-- Good: Using semantic strong -->
<strong>Important</strong>
09 · Forms (Basic)
Theory: Forms collect user input — text, emails, passwords, choices. Every form element should have a label for accessibility.
<form>
<label>Name:
<input type="text" name="username">
</label>
<br><br>
<label>Email:
<input type="email" name="email" required>
</label>
<br><br>
<label>Password:
<input type="password" name="pass">
</label>
<br><br>
<button type="submit">Send</button>
</form>
Common Input Types
text— Regular textemail— Email validationpassword— Hidden textnumber— Numbers onlydate— Date pickertel— Phone numberurl— Website URLcheckbox— On/off choiceradio— One choice from many
Example with different inputs
<form action="/submit" method="post">
<label for="fullname">Full Name:</label>
<input id="fullname" type="text" name="name" required>
<br><br>
<label for="useremail">Email:</label>
<input id="useremail" type="email" name="email" required>
<br><br>
<label for="msg">Message:</label><br>
<textarea id="msg" name="message" rows="4" cols="50"></textarea>
<br><br>
<button type="submit">Send Message</button>
</form>
🔒 Form Attributes
action— Where to send form datamethod— How to send (getorpost)required— Makes field mandatoryplaceholder— Hint text inside inputname— Identifier for the dataid— Connects label to input
Every form control needs an associated <label> for accessibility. Screen readers use labels to tell users what each field is for.
10 · Forms (Advanced)
Always include meaningful alt. For decorative images, use empty alt="". Prefer modern formats (webp, avif), and responsive images (srcset/sizes).
<img src="hero.webp" alt="Developer at laptop" width="1200" height="600"
srcset="hero-600.webp 600w, hero-900.webp 900w, hero-1200.webp 1200w"
sizes="(max-width: 800px) 100vw, 800px">
<figure>
<img src="chart.avif" alt="Traffic chart">
<figcaption>Figure 1. Weekly traffic</figcaption>
</figure>
<video controls width="480" preload="metadata" poster="poster.jpg">
<source src="lesson.mp4" type="video/mp4">
<track kind="captions" src="captions.vtt" srclang="en" label="English" default>
Sorry, your browser doesn't support embedded videos.
</video>
11 · File Upload
Theory: Allow users to upload files (images, documents, etc.) through forms. Use type="file" and proper enctype.
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="photo">Choose a photo:</label>
<input type="file" id="photo" name="photo" accept="image/*">
<br><br>
<label for="doc">Choose a document:</label>
<input type="file" id="doc" name="document" accept=".pdf,.doc,.docx">
<br><br>
<button type="submit">Upload Files</button>
</form>
enctype="multipart/form-data"— Required for file uploadsaccept— Limits file types (e.g.,accept="image/*"for images only)multiple— Allows selecting multiple files
<!-- Multiple file upload -->
<form action="/upload" method="post" enctype="multipart/form-data">
<label>Select multiple images:</label>
<input type="file" name="photos" multiple accept="image/jpeg,image/png">
<button type="submit">Upload</button>
</form>
📝 Common MIME Types for Accept
image/*— All imagesimage/jpeg, image/png— Specific image types.pdf— PDF files.doc, .docx— Word documentsvideo/*— All videosaudio/*— All audio files
12 · Lists & Tables (Advanced)
<ul><li>unordered</li><li>list</li></ul>
<ol start="3" reversed><li>third</li><li>second</li></ol>
<dl><dt>HTML</dt><dd>HyperText Markup Language</dd></dl>
<table>
<caption>Monthly Revenue</caption>
<thead><tr><th scope="col">Month</th><th scope="col">EUR</th></tr></thead>
<tbody>
<tr><th scope="row">Jan</th><td>3,200</td></tr>
<tr><th scope="row">Feb</th><td>3,580</td></tr>
</tbody>
<tfoot><tr><th scope="row">Total</th><td>6,780</td></tr></tfoot>
</table>
Use scope, headers, captions, and summary text for accessible data tables.
08 · Forms (Deep Dive)
HTML forms collect user input. Always associate labels, use proper types, constraints, and accessible help.
<form action="/subscribe" method="post" novalidate>
<fieldset>
<legend>Newsletter</legend>
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<label for="name">Full name</label>
<input id="name" name="name" type="text" minlength="2" maxlength="60">
<label for="plan">Plan</label>
<select id="plan" name="plan" required>
<option value="">— Select —</option>
<option>Free</option>
<option>Pro</option>
</select>
<label>Topics (choose at least one)</label>
<div role="group" aria-labelledby="topics">
<label><input type="checkbox" name="t" value="html" required> HTML</label>
<label><input type="checkbox" name="t" value="css"> CSS</label>
<label><input type="checkbox" name="t" value="js"> JS</label>
</div>
<label for="bio">Short bio</label>
<textarea id="bio" name="bio" rows="4" placeholder="Tell us about you…"></textarea>
<button>Subscribe</button>
</fieldset>
</form>
- Labeling: Use
<label for>tied to inputid. - Validation:
required,pattern,min/max,minlength/maxlength. - Autocomplete: correct tokens (e.g.,
email,name,address-line1). - Helpers:
<small id="hint">…</small>referenced viaaria-describedby.
14 · Video & Audio
Theory: HTML5 provides native <video> and <audio> elements for embedding media without plugins.
Video Element
<video width="400" height="300" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.webm" type="video/webm">
Your browser doesn't support video.
</video>
Common Attributes:
controls— Show play/pause buttonsautoplay— Start automaticallyloop— Repeat when finishedmuted— Start mutedposter— Thumbnail image
Audio Element
<audio controls>
<source src="song.mp3" type="audio/mpeg">
<source src="song.ogg" type="audio/ogg">
Your browser doesn't support audio.
</audio>
Best Practices:
- Provide multiple formats for compatibility
- Always include fallback text
- Use
preload="metadata"to save bandwidth - Add captions/subtitles for accessibility
<!-- Video with poster and captions -->
<video width="640" height="360" controls poster="preview.jpg">
<source src="lesson.mp4" type="video/mp4">
<track kind="subtitles" src="subtitles-en.vtt" srclang="en" label="English">
<track kind="subtitles" src="subtitles-es.vtt" srclang="es" label="Español">
Your browser does not support the video tag.
</video>
📺 Video File Formats
- MP4 (.mp4) — Most compatible, works everywhere
- WebM (.webm) — Better compression, open source
- Ogg (.ogv) — Open source alternative
🎵 Audio File Formats
- MP3 (.mp3) — Most universal
- WAV (.wav) — Uncompressed, high quality
- Ogg (.ogg) — Open source, good compression
15 · Meta Tags (Basic)
Theory: Meta tags provide information about your webpage to browsers and search engines. They go in the <head> section.
<head>
<!-- Character encoding - ALWAYS include this first -->
<meta charset="UTF-8">
<!-- Responsive viewport for mobile -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Page title (shows in browser tab) -->
<title>My Awesome Website</title>
<!-- Page description (shows in search results) -->
<meta name="description" content="Learn web development with easy tutorials and examples">
<!-- Keywords for SEO -->
<meta name="keywords" content="HTML, CSS, JavaScript, web development">
<!-- Author information -->
<meta name="author" content="Your Name">
</head>
<meta charset="UTF-8">— Enables all characters/emojis<meta name="viewport"...>— Makes site mobile-friendly<title>— Page name (SEO and usability)<meta name="description"...>— Shows in Google search results
🔍 Why Meta Tags Matter
- SEO — Help Google understand your page
- Social Sharing — Control how links look when shared
- Mobile — Make your site responsive
- Browser Behavior — Control caching, rendering
16 · Head, Meta & SEO (Advanced)
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="canonical" href="https://example.com/">
<meta name="description" content="Concise page summary up to ~155 characters.">
<meta property="og:title" content="Page Title">
<meta property="og:type" content="website">
<meta property="og:url" content="https://example.com/">
<meta property="og:image" content="https://example.com/preview.jpg">
<meta name="twitter:card" content="summary_large_image">
<script type="application/ld+json">{
"@context":"https://schema.org",
"@type":"Course",
"name":"HTML Mastery",
"description":"Structured HTML course with interactive runner and quizzes.",
"provider":{"@type":"Organization","name":"Your Brand"}
}</script>
Use one <h1>, descriptive titles, and unique meta descriptions per page.
17 · HTML5 Semantic Elements
Theory: Semantic elements clearly describe their meaning to both the browser and developer. Use them for better accessibility, SEO, and code readability.
Site or section header. Contains logo, nav, intro content.
Navigation links. Main menus, breadcrumbs, pagination.
Main content. Only one per page. Skips repeating elements.
Self-contained content. Blog post, news article, comment.
Thematic grouping. Chapters, tabs, content sections.
Related content. Sidebars, call-outs, tangential info.
Section or page footer. Copyright, links, contact info.
Self-contained illustration. Image with caption.
Date/time. Machine-readable format for events, posts.
<!-- Good semantic structure -->
<body>
<header>
<h1>My Blog</h1>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
<main>
<article>
<header>
<h2>Article Title</h2>
<time datetime="2025-01-15">January 15, 2025</time>
</header>
<p>Article content...</p>
<footer>
<p>Tags: HTML, Web Development</p>
</footer>
</article>
<aside>
<h3>Related Posts</h3>
<ul>...</ul>
</aside>
</main>
<footer>
<p>© 2025 My Blog</p>
</footer>
</body>
✅ Benefits of Semantic HTML
- SEO — Search engines understand content better
- Accessibility — Screen readers navigate easily
- Maintainability — Code is easier to read and update
- Consistency — Team members understand structure
18 · Accessibility Basics (a11y)
Theory: Accessibility means making your website usable by everyone, including people with disabilities. This includes blind users with screen readers, users who can't use a mouse, and users with other limitations.
Key Principles
- Use semantic HTML —
<button>not<div> - Alt text for images — Describe what's in the image
- Labels for forms — Connect every input to a label
- Keyboard navigation — Everything should work with Tab/Enter
- Color contrast — Text must be readable
<!-- Good accessibility -->
<button>Click Me</button>
<img src="cat.jpg" alt="Orange cat sleeping">
<label for="email">Email:</label>
<input id="email" type="email">
<!-- Bad accessibility -->
<div onclick="...">Click Me</div>
<img src="cat.jpg"> <!-- No alt! -->
<input type="email"> <!-- No label! -->
- ✅ All images have meaningful
alttext - ✅ All form inputs have labels
- ✅ Headings follow logical order (h1 → h2 → h3)
- ✅ Links have descriptive text
- ✅ Can navigate entire site with keyboard only
- ✅ Focus indicators are visible
- ✅ Colors have sufficient contrast
<!-- Skip navigation link (helps keyboard users) -->
<a href="#main-content" class="skip-link">Skip to main content</a>
<!-- Accessible button with ARIA label -->
<button aria-label="Close dialog">✕</button>
<!-- Form with proper labels -->
<form>
<label for="username">Username:</label>
<input id="username" type="text" required aria-required="true">
</form>
🔍 Why Accessibility Matters
- 15% of people have some form of disability
- Legal requirement in many countries
- Better UX for everyone (not just disabled users)
- Better SEO — accessible sites rank higher
- Wider audience — more potential customers
19 · Accessibility (Advanced)
- Provide skip links:
<a href="#main" class="pill">Skip to content</a> - Contrast ≥ 4.5:1 for text
- Focus states visible; no keyboard traps
- Use semantic elements and ARIA only when needed
- Announce dynamic updates with
aria-livewhere appropriate
41 · Performance
- Optimize images (responsive, modern formats)
- Inline critical CSS for small pages; defer non‑critical scripts
- Preload critical assets; preconnect to third‑party origins
- Minimize DOM size; avoid layout thrashing
20 · Colors
Use color keywords, HEX, RGB, HSL. Prefer CSS for styling, not HTML attributes.
<p style="color:#3b82f6; background:hsl(220 50% 10%)">Readable contrast matters.</p>
21 · Formatting
Semantic inline elements for meaning: <strong>, <em>, <mark>, <small>, <del>, <ins>, <sup>, <sub>.
<p>Water: H<sub>2</sub>O; E = mc<sup>2</sup></p>
23 · Class vs ID
id: unique per page, used for anchors and JS hooks.class: reusable, used for styling groups of elements.
<div id="hero" class="card primary">…</div>
24 · Block vs Inline
Block elements start on a new line (e.g., <div>, <p>). Inline flow within a line (e.g., <span>, <a>).
28 · Favicon
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
29 · File Paths
<img src="./img/pic.jpg"> <!-- relative -->
<img src="/img/pic.jpg"> <!-- root-relative -->
<a href="https://example.com">external</a>
30 · Iframes (Safely)
<iframe src="/guide.html" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-scripts allow-same-origin"></iframe>
25 · Entities & Symbols
< > & © ™ 🚀 (🚀)
26 · Emojis & Charset
<meta charset="utf-8"> <!-- enables emojis: 😊 -->
31 · Responsive Layout
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:1rem}
</style>
<div class="grid"><div class="card">A</div><div class="card">B</div></div>
17 · HTML5 Semantic Elements
Prefer meaningful elements: <header>, <nav>, <main>, <article>, <section>, <aside>, <footer>, <figure>, <figcaption>.
27 · Data Attributes
Theory: Data attributes let you store custom data on HTML elements. Use them to pass data to JavaScript or style with CSS.
<!-- Store custom data -->
<button data-user-id="12345" data-role="admin" data-action="delete">
Delete User
</button>
<div data-theme="dark" data-language="en" data-version="2.0">
Content here
</div>
Access in JavaScript
const btn = document.querySelector('button');
// Read data attributes
console.log(btn.dataset.userId); // "12345"
console.log(btn.dataset.role); // "admin"
console.log(btn.dataset.action); // "delete"
// Set data attributes
btn.dataset.status = "active";
btn.dataset.priority = "high";
Use in CSS
/* Style based on data attributes */
[data-theme="dark"] {
background: #000;
color: #fff;
}
[data-status="active"] {
border: 2px solid green;
}
/* Show data in CSS */
button::after {
content: attr(data-action);
}
- Must start with
data- - Use lowercase and hyphens:
data-user-name - In JavaScript, convert to camelCase:
dataset.userName - Store simple strings only
<!-- Real-world example: Product card -->
<div class="product"
data-product-id="ABC123"
data-price="29.99"
data-category="electronics"
data-in-stock="true">
<h3>Wireless Mouse</h3>
<button class="add-to-cart">Add to Cart</button>
</div>
<script>
document.querySelector('.add-to-cart').addEventListener('click', e => {
const product = e.target.closest('.product');
const id = product.dataset.productId;
const price = product.dataset.price;
console.log(`Adding product ${id} for $${price}`);
});
</script>
🎯 Common Use Cases
- Store IDs for JavaScript interaction
- Configuration values (theme, language, settings)
- State information (active, loading, error)
- Tooltips and extra info
- Filter/sort criteria
32 · Graphics: Canvas & SVG
<svg viewBox="0 0 100 10" width="300">
<circle cx="5" cy="5" r="4" fill="currentColor" />
<text x="12" y="8">SVG text</text>
</svg>
<canvas id="c" width="200" height="80"></canvas>
<script>const ctx=c.getContext('2d');ctx.fillRect(10,10,60,40)</script>
33 · HTML5 APIs Overview
Theory: HTML5 introduced many powerful JavaScript APIs that let you build modern web applications with advanced features.
Get user's location (with permission)
navigator.geolocation
.getCurrentPosition(
pos => console.log(pos.coords)
);
Store data locally in browser
localStorage.setItem('theme', 'dark');
let theme = localStorage.getItem('theme');
Draw graphics with JavaScript
const ctx = canvas.getContext('2d');
ctx.fillRect(10, 10, 100, 50);
Process and synthesize audio
const audio = new Audio('song.mp3');
audio.play();
Run scripts in background
const worker = new Worker('task.js');
worker.postMessage(data);
Make network requests
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data));
Real-time communication (video chat)
Drag elements and files
Show system notifications
new Notification('Hello!', {
body: 'Message text'
});
- Local Storage — Save user data
- Geolocation — Location-based features
- Fetch — Load data from servers
- Canvas — Draw graphics and charts
- History API — Change URL without reload
💡 When to Use These APIs
- Storage — Remember user preferences, save game progress
- Geolocation — Weather apps, store locators, maps
- Canvas — Games, data visualizations, image editing
- Workers — Heavy calculations without freezing UI
- Notifications — Chat apps, reminders, updates
34 · Geolocation API
<button onclick="navigator.geolocation.getCurrentPosition(p=>alert(p.coords.latitude+','+p.coords.longitude))">Locate Me</button>
Note Requires HTTPS and user permission.
35 · Web Storage (localStorage/sessionStorage)
<script>localStorage.setItem('theme','dark');alert(localStorage.getItem('theme'))</script>
36 · Web Workers (basic)
// main.js
const w = new Worker(URL.createObjectURL(new Blob([`onmessage=e=>postMessage(e.data*2)`])));
w.onmessage = e => alert(e.data); w.postMessage(21);
37 · Server-Sent Events (concept)
<script>const es=new EventSource('/events');es.onmessage=e=>console.log(e.data)</script>
38 · YouTube & Embeds
<iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID" title="YouTube video" loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
39 · <template> & Slots
<template id="row"><tr><td></td></tr></template>
<script>const t=row.content.cloneNode(true);t.querySelector('td').textContent='Hi';document.body.append(t);</script>
40 · Microdata & RDFa (alt to JSON-LD)
<div itemscope itemtype="https://schema.org/Course">
<span itemprop="name">HTML Mastery</span>
</div>
42 · Best Practices & Final Tips
Theory: Follow these guidelines to write clean, professional, maintainable HTML that works well everywhere.
- Use semantic HTML (
<header>,<nav>,<main>) - Add
alttext to all images - Label every form input
- Keep one
<h1>per page - Use lowercase for tags and attributes
- Close all tags properly
- Indent your code for readability
- Validate your HTML regularly
- Test on multiple browsers
- Make your site responsive
- Don't use tables for layout (use CSS instead)
- Don't use
<br>for spacing (use CSS) - Don't skip heading levels (h1 → h3)
- Don't use inline styles everywhere
- Don't forget
<!DOCTYPE html> - Don't use deprecated tags (
<font>,<center>) - Don't make clickable
<div>s (use<button>) - Don't ignore accessibility
- Don't use duplicate IDs
- Don't leave images without alt text
- ✅ Validate HTML at validator.w3.org
- ✅ Check accessibility with screen reader or WAVE tool
- ✅ Test on mobile devices
- ✅ Verify all links work
- ✅ Check images load and have alt text
- ✅ Test forms work correctly
- ✅ Optimize images for web
- ✅ Add proper meta tags
- ✅ Check page loads fast
- ✅ Test in different browsers
<!-- GOOD HTML EXAMPLE -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Descriptive Page Title</title>
<meta name="description" content="Clear page description">
</head>
<body>
<header>
<h1>Main Title</h1>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
<main>
<article>
<h2>Article Heading</h2>
<p>Content with proper structure.</p>
<img src="photo.jpg" alt="Descriptive text">
</article>
</main>
<footer>
<p>© 2025 My Site</p>
</footer>
</body>
</html>
🎯 Key Principles Summary
- Semantic — Use meaningful tags
- Accessible — Works for everyone
- Valid — Follows HTML standards
- Responsive — Works on all devices
- Fast — Loads quickly
- Secure — Protects users
- Maintainable — Easy to update
📚 Keep Learning
HTML is just the beginning! Next steps:
- Master CSS for styling and layout
- Learn JavaScript for interactivity
- Study responsive design
- Understand web accessibility deeply
- Learn a framework (React, Vue)
- Build real projects constantly
43 · Live Code Runner
44 · Quick Quiz
45 · Glossary
A building block (e.g.,
<p>).Extra info (e.g.,
alt, href).Conveys meaning (e.g.,
<nav>).Accessibility hooks for assistive tech.
Visible area of a page.
Preferred URL for SEO.
46 · Roadmap & Resources
- HTML Foundations (this page)
- CSS Essentials → layout, flexbox, grid
- Accessible Components (buttons, dialogs, nav)
- Forms UX & validation (client & server)
- Performance & SEO playbook
Bookmarks: MDN Web Docs, WHATWG HTML Standard, a11yproject.com.
22 · Comments