CodeNotes Visual Notes

HTML Notes: Beginner to Advanced

Learn HTML step by step with simple theory, visual diagrams, live examples you can see instantly, practice exercises with solutions and the most important interview questions.

16 chapters32 exercises57 Q&ALive outputFree
Chapter 1Beginner

What is HTML?

How the web works and where HTML fits next to CSS and JavaScript.

HTML (HyperText Markup Language) is the standard language used to describe the structure and meaning of content on a web page. It is a markup language, not a programming language: it has no loops, variables or logic. Instead it labels content — this is a heading, this is a paragraph, this is a link.

When you open a website, your browser sends a request to a server. The server returns an HTML document. The browser parses that document into a tree of objects called the DOM (Document Object Model) and paints it on screen. CSS files then style that tree, and JavaScript makes it interactive.

Think of a web page as a house: HTML is the bricks and rooms (structure), CSS is the paint and furniture (presentation), and JavaScript is the electricity and plumbing (behaviour).

The current version is the HTML Living Standard (commonly called HTML5), maintained by WHATWG. It is updated continuously rather than released in numbered versions.

Browser

you type URL

request→

Server

sends index.html

response→

DOM tree

parsed HTML

+CSS +JS→

Screen

painted page

HTML

Structure · bricks

CSS

Style · paint

JavaScript

Behaviour · wiring

Diagram · What is HTML?

Remember

  • HTML = structure, CSS = style, JS = behaviour
  • Browsers turn HTML into the DOM
  • Files use the .html extension
  • HTML is not case-sensitive, but lowercase is the convention

Examples

Your first web page

<!DOCTYPE html>
<html>
  <body>
    <h1>Hello, CodeNotes!</h1>
    <p>This is my first web page.</p>
  </body>
</html>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Create a file named index.html that shows your name as a heading and one sentence about yourself.

2In one line each, explain the role of HTML, CSS and JavaScript.

Important questions

Is HTML a programming language?

No. HTML is a markup language. It describes content and structure but cannot perform calculations, make decisions or repeat actions.

What is the DOM?

The Document Object Model is the in-memory tree the browser builds from your HTML. CSS and JavaScript work with this tree, not the raw text.

Who maintains HTML today?

The WHATWG (Web Hypertext Application Technology Working Group) maintains the HTML Living Standard.

Chapter 2Beginner

Document Structure & Syntax

Tags, elements, attributes, nesting and the boilerplate every page needs.

An element usually has an opening tag, content and a closing tag: <p>Hello</p>. The tag name goes inside angle brackets, and the closing tag has a forward slash.

Attributes give extra information to an element and are written inside the opening tag as name="value" pairs, for example <a href="https://thecodenotes.com">. Some attributes are boolean: just writing them turns them on (disabled, required, checked).

Void (empty) elements have no content and no closing tag: <br>, <hr>, <img>, <input>, <meta>, <link>. Writing <br /> is allowed but not required in HTML.

Elements must be nested correctly — the last opened is the first closed. <p><strong>Hi</strong></p> is correct; <p><strong>Hi</p></strong> is wrong.

Every page starts with <!DOCTYPE html>, which tells the browser to use standards mode. The <html> root contains exactly two children: <head> (information about the page) and <body> (what users see).

Anatomy of an element

<a href="/tools">

opening tag + attribute

Tools

content

</a>

closing tag

└──────── the whole thing is the element ────────┘

Diagram · Document Structure & Syntax

Remember

  • <!DOCTYPE html> must be the first line
  • <head> = metadata, <body> = visible content
  • Attribute values should be in double quotes
  • Comments: <!-- like this -->

Examples

Standard boilerplate

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Page</title>
</head>
<body>
  <!-- Visible content goes here -->
  <h1>Welcome</h1>
  <p>Line one<br>Line two</p>
  <hr>
  <p>After the divider.</p>
</body>
</html>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Find and fix the nesting mistake: <p><em>Learn <strong>HTML</em> today</strong></p>

2Write the full boilerplate for a page titled "Practice" in Hindi (language code hi).

Important questions

Difference between a tag and an element?

A tag is the marker in angle brackets (<p> or </p>). An element is the whole thing: opening tag + content + closing tag.

What happens if you omit <!DOCTYPE html>?

The browser switches to quirks mode, emulating old buggy behaviour, which can break layout and CSS.

Why add lang to <html>?

It helps screen readers pronounce text correctly, helps search engines, and enables correct hyphenation and translation.

Chapter 3Beginner

Headings, Paragraphs & Text Formatting

Organising text with headings and giving words meaning with inline elements.

HTML has six heading levels, <h1> to <h6>. <h1> is the main topic of the page — use one per page. Headings form an outline, so do not skip levels just to get a smaller font; use CSS for size.

<p> creates a paragraph. Browsers collapse multiple spaces and line breaks in your source into a single space, so formatting must come from elements or CSS. <pre> preserves whitespace exactly.

Semantic inline elements add meaning: <strong> (strong importance, bold), <em> (emphasis, italic), <mark> (highlight), <small> (side comments), <del>/<ins> (removed/inserted text), <sub>/<sup> (subscript/superscript), <code> (code), <kbd> (keyboard input), <abbr> (abbreviation), <q> (short quote) and <blockquote> (long quote).

<b> and <i> still exist but carry no extra importance: <b> draws attention (e.g. keywords), <i> marks alternate voice (e.g. a technical term or foreign word).

h1Page title
h2Main section
h3Sub-section
h4Detail
h5Minor
h6Smallest

Headings form an outline — like a book's table of contents.

Diagram · Headings, Paragraphs & Text Formatting

Remember

  • One <h1> per page
  • Never skip heading levels
  • <strong> > <b> when meaning matters
  • Whitespace collapses except in <pre>

Examples

Formatting showcase

<h1>Chemistry Notes</h1>
<h2>Water</h2>
<p>Water is H<sub>2</sub>O. Area is r<sup>2</sup>.</p>
<p><strong>Warning:</strong> do not <em>ever</em> mix these.</p>
<p>Price: <del>₹500</del> <ins>₹50</ins></p>
<p>Press <kbd>Ctrl</kbd> + <kbd>S</kbd> to save.</p>
<p>Use <code>console.log()</code> to debug.</p>
<p><abbr title="HyperText Markup Language">HTML</abbr> is <mark>fun</mark>.</p>
<blockquote>Talk is cheap. Show me the code. — Linus Torvalds</blockquote>
<pre>
  Spaces   are
     kept here
</pre>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Write the formula E = mc² and the chemical formula CO₂ using HTML.

2Create a recipe page outline: h1 for the dish, h2 for Ingredients and Steps, and an h3 for 'Tips' inside Steps.

Important questions

<strong> vs <b>?

Both look bold. <strong> means the text is important (screen readers may stress it); <b> is only visually offset with no extra importance.

Why not use headings to make text big?

Headings define the document outline used by search engines and assistive technology. Use CSS font-size for visual size.

How do you show < or > literally?

Use entities: &lt; and &gt;. Also &amp; for &, &quot; for " and &nbsp; for a non-breaking space.

Chapter 5Beginner

Images & Figures

img, alt text, dimensions, figures and image formats.

<img> is a void element that embeds an image. src is the file path and alt is the text alternative, read by screen readers and shown if the image fails. Decorative images should use alt="".

Always set width and height attributes. The browser reserves space before the image loads, preventing layout shift (a Core Web Vitals metric).

loading="lazy" delays off-screen images until the user scrolls near them, saving bandwidth.

<figure> groups an image (or code, chart, quote) with a caption in <figcaption>.

Formats: JPEG for photos, PNG for transparency/screenshots, SVG for icons and logos (scales infinitely), WebP and AVIF for modern compressed images, GIF for simple animation.

Remember

  • alt is required — empty for decoration
  • Set width + height to avoid layout shift
  • Use loading="lazy" below the fold
  • Prefer WebP/AVIF for size

Examples

Image with caption

<figure>
  <img src="https://picsum.photos/id/0/480/300"
       alt="Laptop on a wooden desk"
       width="480" height="300" loading="lazy">
  <figcaption>Fig 1: A typical coding setup.</figcaption>
</figure>
<img src="missing.png" alt="This text shows when the image fails" width="200" height="60">

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Write good alt text for: (a) a company logo that links home, (b) a decorative divider swirl.

2Add a lazy-loaded image of a chart inside a figure with a caption 'Sales in 2026'.

Important questions

What is alt text for?

Accessibility (screen readers), fallback when images fail, and SEO — search engines read it to understand images.

Why specify width and height?

So the browser can calculate the aspect ratio and reserve space, avoiding content jumping (Cumulative Layout Shift).

When should you use SVG?

For logos, icons and illustrations made of shapes — SVG is sharp at any size and usually tiny.

Chapter 6Beginner

Lists

Unordered, ordered, description and nested lists.

<ul> is an unordered (bulleted) list; use it when order doesn't matter. <ol> is an ordered (numbered) list for steps or rankings. Each item is an <li>.

<ol> accepts type (1, a, A, i, I), start (first number) and reversed attributes.

<dl> is a description list: <dt> is the term and <dd> its description — perfect for glossaries and FAQs.

Lists can be nested by placing a new <ul> or <ol> inside an <li>, never directly inside another <ul>.

Navigation menus are typically a <ul> of links inside <nav>, then styled horizontally with CSS.

<ul>

• Mango

• Banana

order doesn't matter

<ol>

1. Install

2. Code

sequence matters

<dl>

HTML

Structure

term → description

Diagram · Lists

Remember

  • Only <li> can be a direct child of <ul>/<ol>
  • Nest lists inside an <li>
  • <dl>/<dt>/<dd> for term–definition pairs

Examples

Three list types + nesting

<h3>Shopping</h3>
<ul>
  <li>Fruits
    <ul><li>Mango</li><li>Banana</li></ul>
  </li>
  <li>Milk</li>
</ul>
<h3>Steps</h3>
<ol type="i" start="3">
  <li>Install VS Code</li>
  <li>Create index.html</li>
</ol>
<h3>Glossary</h3>
<dl>
  <dt>HTML</dt><dd>Structure of a web page</dd>
  <dt>CSS</dt><dd>Styling of a web page</dd>
</dl>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Create an ordered top-3 countdown (3, 2, 1) of your favourite languages.

2Make a syllabus: Frontend (HTML, CSS, JS) and Backend (Node, SQL) as a nested list.

Important questions

Can you put a <p> directly inside a <ul>?

No. Only <li> (and script-supporting elements) can be direct children. Put the <p> inside an <li>.

How to start numbering at 5?

<ol start="5">. You can also set value="10" on an individual <li>.

Chapter 7Intermediate

Tables

Rows, columns, headers, captions, colspan/rowspan and accessible data tables.

Tables are for tabular data — not for page layout (use CSS Grid/Flexbox for layout).

<table> contains rows <tr>. Cells are <td> (data) or <th> (header). Group rows with <thead>, <tbody> and <tfoot> for meaning, styling and printing.

<caption> is the table's title and must be the first child. The scope attribute on <th> (col or row) tells screen readers which cells a header applies to.

colspan makes a cell span multiple columns; rowspan spans multiple rows. When a cell spans, remove the cells it covers from the following markup.

<colgroup> and <col> let you style whole columns at once.

<table>whole grid
<caption>title
<thead>header rows
<tr>one row
<th>header cell
<tbody>data rows
<td>data cell
<tfoot>totals
colspan="2" →
rowspan="2" ↓
td
td
Diagram · Tables

Remember

  • Tables = data, never layout
  • Use <th scope> for accessibility
  • <caption> describes the table
  • colspan → across, rowspan → down

Examples

Timetable with spans

<table border="1" cellpadding="6">
  <caption>Weekly Timetable</caption>
  <thead>
    <tr><th scope="col">Day</th><th scope="col">9 AM</th><th scope="col">10 AM</th></tr>
  </thead>
  <tbody>
    <tr><th scope="row">Mon</th><td colspan="2">HTML Workshop</td></tr>
    <tr><th scope="row">Tue</th><td rowspan="2">CSS</td><td>JS</td></tr>
    <tr><th scope="row">Wed</th><td>Python</td></tr>
  </tbody>
  <tfoot>
    <tr><td colspan="3">Total: 6 hours</td></tr>
  </tfoot>
</table>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Build a marksheet table with columns Name, Maths, Science and a footer row showing class average.

2Create a 3×3 table where the first cell spans all three columns as a title.

Important questions

Why not use tables for layout?

They are not responsive, confuse screen readers (which announce rows/columns), and mix content with presentation.

Difference between <th> and <td>?

<th> is a header cell (bold and centred by default, semantically a label); <td> holds data.

What does scope do?

It links a header to its column (scope="col") or row (scope="row") so assistive tech can read cells with context.

Chapter 8Intermediate

Forms & Input Types

Collecting user input: form, label, input types, select, textarea and buttons.

<form> wraps controls that send data. action is the URL that receives data and method is GET (data in URL — for searches) or POST (data in body — for logins, uploads).

Every control needs a name — that becomes the key in the submitted data (name=value).

<label for="id"> connects text to a control. Clicking the label focuses the input and screen readers announce it. You can also wrap the input inside the label.

Input types give free validation and the right mobile keyboard: text, email, password, number, tel, url, search, date, time, datetime-local, month, week, color, range, file, checkbox, radio, hidden.

Other controls: <textarea> (multi-line), <select> with <option>/<optgroup> (dropdown), <datalist> (suggestions), <button> (type submit, reset or button), and <fieldset> + <legend> to group related fields.

Radio buttons sharing the same name form a group where only one can be chosen; checkboxes allow many.

<label>

for="email"

links to→

<input>

id + name

submit→

<form>

action + method

name=value→

Server

GET → /search?q=html  ·  POST → data hidden in request body

Diagram · Forms & Input Types

Remember

  • Always pair inputs with <label>
  • name is required to submit a value
  • GET for reads, POST for writes
  • <button> defaults to type="submit" inside a form

Examples

Registration form

<form action="/register" method="post">
  <fieldset>
    <legend>Student details</legend>
    <label for="nm">Full name</label><br>
    <input id="nm" name="name" type="text" placeholder="Aarav Sharma"><br>
    <label for="em">Email</label><br>
    <input id="em" name="email" type="email"><br>
    <label for="dob">Date of birth</label><br>
    <input id="dob" name="dob" type="date">
  </fieldset>
  <p>Course:
    <label><input type="radio" name="course" value="html"> HTML</label>
    <label><input type="radio" name="course" value="css"> CSS</label>
  </p>
  <label><input type="checkbox" name="news"> Send me updates</label><br>
  <label for="city">City</label>
  <select id="city" name="city">
    <optgroup label="East"><option>Kolkata</option><option>Ranchi</option></optgroup>
    <optgroup label="West"><option>Mumbai</option></optgroup>
  </select><br>
  <label for="lvl">Skill level</label>
  <input id="lvl" type="range" name="level" min="1" max="10"><br>
  <textarea name="msg" rows="3" cols="30" placeholder="Message"></textarea><br>
  <button type="submit">Register</button>
  <button type="reset">Clear</button>
</form>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Create a login form with email, password, a 'Remember me' checkbox and a submit button, sent with POST to /login.

2Make a search form that sends ?q=... to /search using GET.

Important questions

GET vs POST?

GET appends data to the URL, can be bookmarked and cached, limited in length — use for searching. POST sends data in the request body — use for sensitive or state-changing actions.

What does the name attribute do?

It is the key under which the control's value is submitted. Without name, the value is not sent.

placeholder vs label?

placeholder is a hint that disappears when typing and is not a replacement for a label. Always use a real <label>.

Radio vs checkbox?

Radios with the same name allow one choice; checkboxes allow zero or more.

Chapter 9Intermediate

Form Validation

Built-in validation with required, min/max, pattern and more.

HTML can validate input in the browser before submission with no JavaScript. The browser shows an error message and blocks submission.

required — field must be filled. minlength/maxlength — text length. min/max/step — number and date ranges. pattern — a regular expression the value must match. type=email/url — format checks.

The :valid and :invalid CSS pseudo-classes let you style fields by state; :user-invalid only applies after the user interacts.

novalidate on <form> disables built-in validation (useful when you validate with JavaScript). formnovalidate on a button skips validation for that button (e.g. 'Save draft').

Important: client-side validation is for user experience only. Always validate again on the server — anyone can bypass the browser.

Remember

  • required, pattern, min, max, minlength
  • title gives a hint on pattern errors
  • Never trust client validation alone

Examples

Validated sign-up

<form>
  <label>Username (3–12 letters)
    <input name="u" required minlength="3" maxlength="12" pattern="[A-Za-z]+" title="Letters only">
  </label><br>
  <label>Age (13–99)
    <input name="age" type="number" min="13" max="99" required>
  </label><br>
  <label>Indian mobile
    <input name="phone" type="tel" pattern="[6-9][0-9]{9}" placeholder="9876543210">
  </label><br>
  <button>Submit</button>
</form>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Create a PIN code field that accepts exactly 6 digits and is required.

2Create a quantity field allowing 1 to 10 in steps of 1, defaulting to 1.

Important questions

Is HTML validation secure?

No. It improves UX but can be removed via DevTools. Server-side validation is mandatory.

What is inputmode?

A hint for which virtual keyboard to show (numeric, decimal, tel, email, url, search) without changing validation.

Chapter 10Intermediate

Semantic HTML & Page Layout

header, nav, main, article, section, aside, footer — and why div isn't enough.

Semantic elements describe the meaning of their content. A <div> says nothing; a <nav> says 'this is navigation'. This helps search engines, screen readers (landmark navigation) and other developers.

<header> — introductory content or a site/section header. <nav> — major navigation links. <main> — the unique main content (one per page). <article> — self-contained content that makes sense alone (blog post, product card, comment). <section> — a thematic group, usually with a heading. <aside> — tangential content (sidebar, related links). <footer> — footer of the page or a section.

Other semantic elements: <address> (contact info), <time datetime="2026-11-12"> (machine-readable dates), <details>/<summary> (collapsible), <dialog> (modal), <search> (search area), <hgroup> (heading + subtitle).

Use <div> and <span> only as generic containers for styling when no semantic element fits.

<header> logo + <nav>

<main>

<article>

<section>
<section>
<aside>
<footer>
Diagram · Semantic HTML & Page Layout

Remember

  • One <main> per page
  • <article> = can stand alone
  • <section> should have a heading
  • div = last resort container

Examples

Semantic blog layout

<header>
  <h1>CodeNotes Blog</h1>
  <nav><a href="/">Home</a> · <a href="/blog">Blog</a></nav>
</header>
<main>
  <article>
    <h2>Learning HTML in 2026</h2>
    <p>Published <time datetime="2026-11-12">12 Nov 2026</time></p>
    <section>
      <h3>Why HTML?</h3>
      <p>Everything on the web starts here.</p>
    </section>
  </article>
  <aside>
    <h3>Related</h3>
    <a href="#">CSS basics</a>
  </aside>
</main>
<footer>
  <address>Contact: <a href="mailto:hi@example.com">hi@example.com</a></address>
  <p>&copy; 2026 CodeNotes</p>
</footer>

Output

Collapsible FAQ with details

<details open>
  <summary>What is HTML?</summary>
  <p>The structure of the web.</p>
</details>
<details>
  <summary>Is it hard?</summary>
  <p>No — you can learn the basics in a week.</p>
</details>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Convert this 'div soup' into semantic HTML: <div class=top><div class=menu>...</div></div><div class=content>...</div><div class=bottom>...</div>

2Mark up a product card as a reusable, standalone unit with image, name, price and a buy button.

Important questions

article vs section?

<article> is self-contained and reusable on its own (e.g. syndicated). <section> groups related content within a larger whole and normally has a heading.

Why does semantic HTML help SEO?

Search engines understand which part is main content, navigation or footer, and can weigh headings and articles correctly.

Can a page have multiple <header> elements?

Yes — one for the page and one inside each article or section. But only one <main>.

Chapter 11Intermediate

Block vs Inline, div & span

How elements flow on the page by default.

Block-level elements start on a new line and take the full available width: <div>, <p>, <h1>–<h6>, <ul>, <section>, <form>, <table>.

Inline elements sit within a line and only take the width of their content: <span>, <a>, <strong>, <em>, <img>, <code>, <input>.

You cannot set width/height or vertical margin on pure inline elements (images and inputs are special 'replaced' inline elements and can be sized).

CSS display can change any element's behaviour (display: block, inline, inline-block, flex, grid, none) — HTML choice is about meaning, CSS about appearance.

class groups elements for styling (many elements can share it); id is unique and is used for fragment links, labels and JavaScript.

Block — new line, full width

<div>
<p>

Inline — flows inside the line

Text <span> more text <a> and <strong> continue.

Diagram · Block vs Inline, div & span

Remember

  • Block = new line, full width
  • Inline = flows in text
  • class reusable, id unique
  • Don't put block elements inside <p>

Examples

Flow demo

<div style="background:#fde7c8">I am a block div</div>
<div style="background:#fbd38d">Another block</div>
<p>Text with <span style="background:#fde7c8">an inline span</span> and
<a href="#">a link</a> sitting in the line.</p>
<p class="note">class="note" can repeat</p>
<p class="note" id="unique">but id="unique" cannot</p>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Highlight the word 'free' in a sentence using a span with class highlight.

2Classify as block or inline: <li>, <label>, <article>, <button>, <h3>, <abbr>.

Important questions

div vs span?

Both are meaningless containers. div is block-level (groups sections); span is inline (wraps part of text).

Why can't a <div> go inside a <p>?

A <p> can only contain phrasing (inline) content. The browser will auto-close the <p> before the <div>, breaking your structure.

Chapter 12Intermediate

Audio, Video & Embeds

Native media players, multiple sources, captions and iframes.

<video> and <audio> play media natively. Add controls to show play/pause. Other attributes: autoplay (usually needs muted), loop, muted, poster (video thumbnail) and preload.

Use multiple <source> elements with different formats; the browser picks the first it supports. Text between the tags is a fallback for very old browsers.

<track kind="captions" src="subs.vtt" srclang="en"> adds captions/subtitles in WebVTT format — essential for accessibility.

<iframe> embeds another page (YouTube, Google Maps). Add a title for accessibility, loading="lazy" for performance, and sandbox/allow to restrict what it can do.

<picture> with <source media> or <img srcset> serves different image files for different screen sizes (responsive images).

<video>

contains

<source> webm

<source> mp4

<track> captions

fallback text

The browser picks the first source it can play.

Diagram · Audio, Video & Embeds

Remember

  • Autoplay requires muted
  • Provide captions with <track>
  • iframe needs a title
  • srcset + sizes for responsive images

Examples

Video, audio and responsive image

<video controls width="320" poster="https://picsum.photos/320/180" muted>
  <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" type="video/webm">
  <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" type="video/mp4">
  Your browser does not support video.
</video>
<audio controls src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
<picture>
  <source media="(min-width: 600px)" srcset="https://picsum.photos/id/1/600/200">
  <img src="https://picsum.photos/id/1/300/200" alt="Responsive laptop photo" width="300" height="200">
</picture>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Embed a background-style video that autoplays silently and loops.

2Embed a YouTube video accessibly and lazily.

Important questions

Why doesn't my video autoplay?

Browsers block autoplay with sound. Add muted (and playsinline on iOS).

picture vs srcset?

srcset lets the browser choose resolutions of the same image. <picture> lets you control art direction or formats (e.g. AVIF then JPEG).

Chapter 13Advanced

The Head, Meta Tags & SEO

title, meta description, viewport, Open Graph, favicons and linking resources.

The <head> holds information about the page that isn't displayed directly but controls how it's indexed, shared and rendered.

<title> appears in the browser tab and as the Google result headline — keep it unique and under ~60 characters. <meta name="description"> is the search snippet (~155 characters).

<meta charset="UTF-8"> supports every language and emoji. <meta name="viewport" content="width=device-width, initial-scale=1"> makes the page responsive on phones.

Open Graph (og:title, og:description, og:image) and Twitter cards control how links look on WhatsApp, Facebook and X.

<link rel="stylesheet">, <link rel="icon">, <link rel="canonical"> (preferred URL to avoid duplicate content), <link rel="preload"> and <link rel="preconnect"> for performance.

Structured data in <script type="application/ld+json"> (schema.org) helps search engines show rich results like ratings, FAQs and prices.

<title>Tab + Google headline
meta descriptionSearch snippet
meta viewportMobile responsiveness
og:*WhatsApp/Facebook previews
link canonicalPreferred URL
ld+jsonRich results
Diagram · The Head, Meta Tags & SEO

Remember

  • Unique title + description per page
  • Viewport meta is required for mobile
  • og:image for social previews
  • canonical prevents duplicates

Examples

Production-ready head

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>HTML Notes – Beginner to Advanced | CodeNotes</title>
  <meta name="description" content="Free visual HTML notes with examples and exercises.">
  <link rel="canonical" href="https://thecodenotes.com/learn/html">
  <link rel="icon" href="/favicon.png">
  <link rel="stylesheet" href="styles.css">
  <meta property="og:title" content="HTML Notes | CodeNotes">
  <meta property="og:image" content="https://thecodenotes.com/og.png">
  <meta name="robots" content="index, follow">
  <script type="application/ld+json">
  { "@context": "https://schema.org", "@type": "Course", "name": "HTML Notes" }
  </script>
</head>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Write the head tags that stop a private page from appearing in Google.

2Write a title and meta description for a page selling Java notes.

Important questions

Does meta keywords help SEO?

No. Google has ignored meta keywords for over a decade.

What does the viewport meta do?

Without it, phones render the page at ~980px and zoom out. With it, the page width matches the device so responsive CSS works.

What is a canonical URL?

The preferred version of a page when several URLs show the same content; search engines consolidate ranking to it.

Chapter 14Advanced

Accessibility (a11y) & ARIA

Building pages everyone can use, including keyboard and screen reader users.

Accessibility means people with visual, motor, hearing or cognitive disabilities can use your site. It's also a legal requirement in many countries and improves SEO and usability for everyone.

The first rule of ARIA: use native HTML first. A <button> is focusable, clickable with Enter/Space and announced as a button for free; a <div onclick> is none of these.

Keyboard: every interactive element must be reachable with Tab. tabindex="0" adds an element to the tab order; tabindex="-1" makes it focusable only via script. Avoid positive tabindex values.

ARIA attributes fill gaps: aria-label (name for icon buttons), aria-labelledby, aria-describedby, aria-expanded (open/closed state), aria-hidden="true" (hide decorative items), aria-live (announce dynamic updates), and role (landmarks or widgets).

Other essentials: meaningful alt text, labels on every input, sufficient colour contrast (4.5:1 for text), a logical heading order, a visible focus outline, and a 'Skip to content' link.

👁

Perceivable

alt text, captions, contrast

⌨

Operable

keyboard, focus, skip links

💡

Understandable

labels, clear errors, lang

🧩

Robust

valid, native HTML, ARIA

The four WCAG principles — POUR

Diagram · Accessibility (a11y) & ARIA

Remember

  • Native elements before ARIA
  • Everything usable by keyboard
  • Icon-only buttons need aria-label
  • Never remove focus outlines without replacement

Examples

Accessible patterns

<a href="#main" class="skip">Skip to content</a>
<button type="button" aria-label="Close menu">✕</button>
<button type="button" aria-expanded="false" aria-controls="menu">Menu</button>
<ul id="menu" hidden><li>Home</li></ul>
<label for="pw">Password</label>
<input id="pw" type="password" aria-describedby="pw-help">
<p id="pw-help">At least 8 characters.</p>
<p aria-live="polite">3 items in cart</p>
<main id="main"><h1>Shop</h1></main>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Fix this: <div onclick="save()"><img src="disk.svg"></div>

2Give a search icon button an accessible name and hide the decorative SVG from screen readers.

Important questions

What is ARIA?

Accessible Rich Internet Applications — attributes that add roles, names and states for assistive technology when native HTML can't express them.

Why is a div button bad?

It isn't focusable, doesn't respond to Enter/Space and isn't announced as a button. You'd need role, tabindex and key handlers to recreate what <button> gives free.

What does aria-hidden="true" do?

It removes the element from the accessibility tree. Never use it on focusable elements.

Chapter 15Advanced

Modern & Interactive Elements

dialog, details, progress, meter, template, canvas, SVG and data attributes.

<dialog> is a native modal/popup. Call showModal() to open it with a backdrop and focus trapping; a <form method="dialog"> inside closes it. The popover attribute creates lightweight popups with no JavaScript.

<progress value="70" max="100"> shows task completion. <meter> shows a measurement within a known range (disk usage, scores) and supports low/high/optimum.

<template> holds HTML that is not rendered until JavaScript clones it — great for repeating cards. <slot> is used inside Web Components.

<canvas> is a drawable bitmap for games and charts via JavaScript. Inline <svg> draws scalable vector graphics with elements like <circle>, <rect> and <path>.

data-* attributes store custom data on any element (data-price="99"), readable in JS as element.dataset.price and in CSS with attribute selectors.

contenteditable makes any element editable; spellcheck, translate, draggable, inert and hidden are other useful global attributes.

Remember

  • Native dialog + popover = no library needed
  • progress = task, meter = measurement
  • data-* for custom data
  • inert disables a region

Examples

Interactive elements

<button popovertarget="tip">Show tip</button>
<div id="tip" popover>Tip: press Esc to close me!</div>

<p>Upload: <progress value="70" max="100">70%</progress></p>
<p>Storage: <meter value="0.8" low="0.3" high="0.7" optimum="0.2">80%</meter></p>

<svg width="160" height="60">
  <rect x="5" y="5" width="60" height="50" rx="8" fill="#f97316"/>
  <circle cx="110" cy="30" r="25" fill="#111"/>
</svg>

<p contenteditable="true" style="border:1px dashed #f97316;padding:4px">Click and edit me</p>

<button data-product="python" data-price="99"
  onclick="alert(this.dataset.product + ' ₹' + this.dataset.price)">Read data-*</button>

<button onclick="document.getElementById('d').showModal()">Open dialog</button>
<dialog id="d">
  <p>Native modal!</p>
  <form method="dialog"><button>Close</button></form>
</dialog>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1Create a quiz score bar showing 7 out of 10 with <meter> where 8+ is optimal.

2Create a confirm-delete dialog with Cancel and Delete buttons that close it.

Important questions

progress vs meter?

<progress> shows how far a task has gone. <meter> shows a static value within a range, like a fuel gauge.

canvas vs SVG?

Canvas is pixel-based and fast for many objects (games). SVG is vector, resolution-independent, part of the DOM and accessible — better for icons and charts with few elements.

What is the template element for?

Storing inert markup that JavaScript clones and inserts later, without rendering or loading its images.

Chapter 16Advanced

Performance, Scripts & Best Practices

Loading scripts properly, resource hints, validation and a professional checklist.

A plain <script> in the head blocks HTML parsing until it downloads and runs. defer downloads in parallel and runs after parsing, in order — ideal for most scripts. async runs as soon as it downloads, in any order — ideal for independent scripts like analytics. type="module" scripts are deferred by default.

Put CSS in the <head> so the page doesn't flash unstyled. Use <link rel="preload"> for critical fonts/images and <link rel="preconnect"> for third-party origins.

Images are usually the heaviest assets: compress them, use modern formats, srcset, width/height and loading="lazy". fetchpriority="high" on the main hero image speeds up Largest Contentful Paint.

Validate your markup with the W3C validator (validator.w3.org). Use lowercase tags, quote attributes, indent consistently and close elements.

Security: never insert untrusted user input as raw HTML (XSS). Use rel="noopener" on external links and sandbox iframes from untrusted sources.

<script>
async
defer

▬ dark = HTML parsing · ▬ light orange = download · ▬ orange = execute

Diagram · Performance, Scripts & Best Practices

Remember

  • Use defer for scripts
  • CSS in head, scripts deferred
  • Lazy-load below-the-fold images
  • Validate with W3C

Examples

Optimised page skeleton

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Fast Page</title>
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link rel="stylesheet" href="styles.css">
  <script src="app.js" defer></script>
  <script src="analytics.js" async></script>
</head>
<body>
  <img src="hero.webp" alt="Hero" width="1200" height="600" fetchpriority="high">
  <img src="footer.webp" alt="Team" width="600" height="300" loading="lazy">
</body>
</html>

Output

Practice exercises

Try each exercise in your own HTML editor before opening the solution.

1You have jquery.js and app.js (which depends on jQuery). Load both without blocking parsing and keep order.

2Final project: build a complete personal portfolio page with header/nav, an about section with image, a projects table, a contact form and a footer — using semantic, accessible, valid HTML.

Hint: Use everything from chapters 2–16. Run it through validator.w3.org.

Important questions

defer vs async?

Both download without blocking. defer runs after HTML parsing, in document order. async runs immediately when downloaded, in any order.

Where should you put <script> tags?

In the <head> with defer (modern best practice), or at the end of <body> for legacy code.

What is XSS?

Cross-site scripting: injecting malicious scripts through untrusted input rendered as HTML. Prevent it by escaping output and never using raw HTML insertion for user data.

Top HTML Interview Questions

Quick revision before exams and interviews.

What are void elements? Name five.

Elements with no content or closing tag: br, hr, img, input, meta, link, source, track, area, base, col, wbr.

What is the difference between HTML and HTML5?

HTML5 added semantic elements (header, article…), native audio/video, canvas, SVG inline, new input types, localStorage APIs and a simple doctype.

What is the difference between id and class?

id is unique on a page and has higher CSS specificity; class can be reused on many elements.

What are global attributes?

Attributes usable on any element: id, class, style, title, lang, dir, hidden, tabindex, data-*, contenteditable, draggable, spellcheck, translate, inert.

What is the purpose of the <meta charset> tag?

It declares the character encoding (UTF-8) so text in all languages displays correctly. It must be within the first 1024 bytes.

What is semantic HTML?

Using elements according to their meaning (nav, article, button) rather than generic divs, improving accessibility, SEO and maintainability.

What are HTML entities?

Codes for reserved or special characters: &lt; &gt; &amp; &quot; &nbsp; &copy; &#8377; (₹).

Difference between <section> and <div>?

<section> is a meaningful thematic grouping with a heading; <div> has no meaning and is only for styling hooks.

How does the browser render an HTML page?

Parse HTML → DOM; parse CSS → CSSOM; combine into render tree; layout (compute positions); paint; composite layers.

What is the iframe sandbox attribute?

It applies restrictions to embedded content (no scripts, forms, popups) unless explicitly allowed with tokens like allow-scripts.

What is localStorage vs sessionStorage?

Browser storage APIs. localStorage persists until cleared; sessionStorage is cleared when the tab closes. Both store strings per origin.

What is the difference between <strong>, <b>, <em>, <i>?

<strong> = importance, <em> = stress emphasis (semantic). <b> = attention without importance, <i> = alternate voice (presentational-ish).