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 ────────┘
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.
<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: < and >. Also & for &, " for " and for a non-breaking space.
Chapter 4Beginner
Links & Navigation
Absolute vs relative URLs, anchors, new tabs, email and phone links.
The anchor element <a> creates hyperlinks — the 'HyperText' in HTML. Its href attribute holds the destination.
An absolute URL contains the full address (https://thecodenotes.com/tools). A relative URL is resolved from the current page: about.html (same folder), ../index.html (one folder up), /contact (from the site root).
Fragment links jump within a page: <a href="#faq"> scrolls to the element with id="faq".
target="_blank" opens a new tab. Modern browsers imply rel="noopener" for it, but adding rel="noopener noreferrer" is still good practice for external links.
Special schemes: mailto: opens an email app, tel: dials a number, and the download attribute asks the browser to download the file instead of opening it.
📁 site/
📄 index.html ← ../index.html
📁 blog/
📄 post.html (you are here)
📁 images/
🖼 cover.png ← images/cover.png
Absolute https://site.com/a
Root-relative /a
Fragment #section
Diagram · Links & Navigation
Remember
Link text should describe the destination — avoid 'click here'
Try each exercise in your own HTML editor before opening the solution.
1Your page is /blog/post.html. Write a relative link to /index.html and to /blog/images/cover.png.
2Build a table of contents with three links that jump to sections with ids intro, usage and faq.
Important questions
Why use rel="noopener" with target="_blank"?
Without it the new page can access window.opener and redirect your original tab (tab-nabbing).
Absolute vs relative URL?
Absolute includes protocol and domain and works from anywhere. Relative depends on the current page location and is shorter and portable within a site.
Can a link wrap block content?
Yes. In HTML5 <a> can wrap block elements like a whole card, as long as it doesn't contain other interactive elements.
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.
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
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.
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.
<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.
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.
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.
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
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.