HTML Home

Welcome to the LearnX HTML course — your complete guide to building modern, semantic, and accessible web pages using HTML5.

  • HTML is the foundation of every website
  • Defines structure and meaning of content
  • Works alongside CSS and JavaScript
  • Easy to learn and beginner-friendly

HTML (HyperText Markup Language) provides the structure of web pages. It tells the browser what each piece of content is — such as headings, paragraphs, images, or links.

In this course, you’ll progress from the basics to advanced topics like semantic layout, forms, and APIs, with practical examples along the way.

Syntax

<tag>Content</tag>
Example

<!DOCTYPE html>
<html>
<head>
  <title>My First Page</title>
</head>
<body>
  <h1>Welcome to LearnX</h1>
  <p>This is my first HTML page.</p>
</body>
</html>
    
Live Editor
  • Always start with a DOCTYPE
  • Keep code properly indented
  • Use semantic tags whenever possible

HTML Introduction

HTML is the standard language used to create web pages and applications. It describes the structure of content using elements and tags.

  • HTML stands for HyperText Markup Language
  • Uses tags to define content
  • Browsers render HTML into visual pages

Every website you visit is built on HTML. It works together with CSS for styling and JavaScript for interactivity.

Syntax

<element>Content</element>
Example

<h1>Hello World</h1>
<p>HTML is easy to learn.</p>
    
Live Editor
  • Write meaningful content inside tags
  • Use lowercase tags for consistency

HTML Editors

To write HTML, you need a text editor. Editors range from simple tools to advanced development environments with helpful features like auto-completion and live preview.

  • HTML can be written in any text editor
  • Code editors improve productivity
  • Live preview helps visualize changes instantly

Beginners can start with basic editors like Notepad, but modern editors provide syntax highlighting, error detection, and extensions that make development faster and easier.

Choosing the right editor depends on your workflow, but most developers prefer lightweight tools with strong plugin ecosystems.

Syntax

Open editor → Create .html file → Write code → Save → Open in browser
Example

<h1>Editing HTML</h1>
<p>This file was created using a code editor.</p>
    
Live Editor
  • Use an editor with syntax highlighting
  • Save files with .html extension
  • Preview frequently in a browser

HTML Basic

A basic HTML document includes essential elements that define the page structure such as the document type, head, and body.

  • Every page starts with a DOCTYPE
  • The head contains metadata
  • The body contains visible content

Understanding the basic structure is the first step to building any webpage. This skeleton ensures browsers interpret your content correctly.

Syntax

<!DOCTYPE html>
<html>
  <head></head>
  <body></body>
</html>
Example

<!DOCTYPE html>
<html>
<head>
  <title>Basic Page</title>
</head>
<body>
  <h1>Hello</h1>
</body>
</html>
    
Live Editor
  • Always include a title element
  • Keep structure clean and readable

HTML Elements

HTML elements are the building blocks of web pages. They define structure and meaning using opening and closing tags.

  • Most elements have opening and closing tags
  • Some elements are self-closing
  • Elements can be nested

Each element has a specific purpose, such as headings, paragraphs, or images. Nesting elements correctly ensures proper rendering.

Syntax

<tag>Content</tag>
Example

<p>This is a paragraph element.</p>
    
Live Editor
  • Avoid overlapping tags
  • Use semantic elements for meaning

HTML Attributes

Attributes provide additional information about elements. They are always written inside the opening tag.

  • Attributes modify element behavior
  • Usually written as name="value"
  • Common attributes include id, class, and style

Attributes allow you to add styles, identifiers, and metadata to elements. They are essential for linking CSS and JavaScript.

Syntax

<element attribute="value">
Example

<a href="https://example.com">Visit Site</a>
    
Live Editor
  • Always quote attribute values
  • Use meaningful class and id names
  • Avoid inline styles when possible

HTML Headings

Headings define the structure and hierarchy of content on a page. They range from h1 (most important) to h6 (least important).

  • Use headings to organize content
  • Only one primary h1 per page is recommended
  • Improves SEO and accessibility

Headings help both users and search engines understand your content structure. They should follow a logical order without skipping levels.

Syntax

<h1>Main Title</h1>
Example

Main Heading

Sub Heading

Section Heading

Live Editor
  • Keep headings concise
  • Maintain logical order

HTML Paragraphs

Paragraph elements are used to display blocks of text content on a webpage.

  • Paragraphs are defined using the p tag
  • Browsers add spacing automatically
  • Use multiple paragraphs for readability

Breaking content into paragraphs improves readability and helps users scan information quickly.

Syntax

<p>Text content</p>
Example

This is a paragraph.

This is another paragraph.

Live Editor
  • Avoid very long paragraphs
  • Use line breaks only when necessary

HTML Styles

Styles allow you to change the appearance of elements using CSS properties like color, font, and spacing.

  • Styles can be inline or external
  • CSS controls presentation
  • Separation of content and design is recommended

While inline styles are useful for quick changes, external CSS files provide better scalability and maintainability.

Syntax

<p style="color:red;">Text</p>
Example

Styled text

Live Editor
  • Prefer external CSS files
  • Avoid excessive inline styles

HTML Formatting

Formatting elements help emphasize text by making it bold, italic, highlighted, or marked as important.

  • Use semantic formatting tags
  • Improves accessibility
  • Helps convey meaning

Formatting is not just visual — tags like strong and em provide meaning that assistive technologies can interpret.

Syntax

<strong>Important</strong>
Example

Bold text

Italic text

Live Editor
  • Use semantic tags instead of purely visual ones
  • Avoid over-formatting text

HTML Quotations

Quotation elements are used to mark up quotes, citations, and references.

  • Use blockquote for long quotes
  • Use q for inline quotes
  • Use cite for references

These elements help browsers and assistive tools understand quoted content.

Syntax

<blockquote>Quote</blockquote>
Example

Learning never exhausts the mind.
Live Editor
  • Use quotation tags semantically
  • Provide sources when possible

HTML Comments

Comments are notes in your code that are not displayed in the browser. They help explain and organize code.

  • Comments are ignored by browsers
  • Useful for documentation
  • Helps team collaboration

Good comments improve maintainability and make it easier to understand code later.

Syntax

<!-- Comment -->
Example


Visible text

Live Editor
  • Write meaningful comments
  • Remove outdated comments

HTML Colors

Colors can be applied using names, HEX, RGB, or HSL values to style text, backgrounds, and borders.

  • HEX and RGB provide precise control
  • Used with CSS properties
  • Important for branding and design

Choosing accessible color combinations improves readability and user experience.

Syntax

style="color:#ff0000;"
Example

Red text

Live Editor
  • Check contrast for accessibility
  • Use consistent color palette

HTML CSS

CSS (Cascading Style Sheets) controls the visual appearance of HTML elements, including layout, colors, and typography.

  • Separates design from content
  • Can be inline, internal, or external
  • Improves maintainability

Using external stylesheets is the recommended approach for scalable projects because it keeps styling consistent across pages.

Syntax

<link rel="stylesheet" href="styles.css">
Example

Styled with CSS

Live Editor
  • Use external CSS for large projects
  • Avoid inline styles when possible

HTML Images

Images enhance visual communication and engagement on web pages.

  • Defined using img tag
  • Always include alt text
  • Supports responsive sizing

The alt attribute improves accessibility and helps search engines understand images.

Syntax

<img src="image.jpg" alt="description">
Example

Sample
    
Live Editor
  • Optimize images for performance
  • Use modern formats like WebP

HTML Favicon

A favicon is a small icon displayed in the browser tab representing your website.

  • Defined in the head section
  • Improves branding
  • Usually 16×16 or 32×32 pixels

Favicons help users quickly identify your site among multiple open tabs.

Syntax

<link rel="icon" href="favicon.ico">
Example


    
Live Editor
  • Use PNG or ICO formats
  • Keep icon simple and recognizable

HTML Page Title

The <title> element defines the title of the document. The title must be text-only, and it is shown in the browser's title bar or in the page's tab.

  • Displayed in the browser tab
  • Crucial for SEO and bookmarks
  • Should be descriptive and concise

A good title helps users understand what the page is about before they even click on it.

Syntax

<title>Page Title</title>
Example

<head>
  <title>HTML Tutorial - LearnX</title>
</head>
    
Live Editor
  • Keep titles between 50-60 characters
  • Use keywords relevant to the page content

HTML Tables

Tables are used to display structured data in rows and columns.

  • Use table, tr, th, td elements
  • Best for tabular data
  • Can be styled with CSS

Tables should not be used for layout; they are meant only for data representation.

Syntax

<table>...</table>
Example

NameAge
Ana22
Live Editor
  • Use th for headers
  • Add captions for accessibility

HTML Lists

Lists group related items together in an ordered or unordered format.

  • Use ul for unordered lists
  • Use ol for ordered lists
  • Use li for items

Lists improve readability and structure content logically.

Syntax

<ul><li>Item</li></ul>
Example

  • HTML
  • CSS
Live Editor
  • Choose list type based on meaning
  • Keep items concise

HTML Block & Inline

HTML elements are categorized as block-level or inline based on how they appear in the layout.

  • Block elements take full width
  • Inline elements take only necessary space
  • Understanding this helps with layout design

Block elements start on a new line and create structure, while inline elements flow within text content.

Syntax

<div>Block</div> <span>Inline</span>
Example

Block element
Inline element
Live Editor
  • Use block elements for layout
  • Use inline for small content pieces

HTML Div

The div element is a container used to group content and apply styles or layout.

  • Most commonly used layout container
  • Works with CSS for styling
  • Has no semantic meaning

Divs are flexible and can hold any type of content, making them essential for page structure.

Syntax

<div>Content</div>
Example

Grouped content
Live Editor
  • Prefer semantic elements when possible
  • Avoid unnecessary nesting

HTML Classes

Classes allow you to apply styles or scripts to multiple elements at once.

  • Reusable styling hooks
  • Can be shared by many elements
  • Defined with class attribute

Classes are essential for CSS styling and JavaScript targeting.

Syntax

<p class="note">Text</p>
Example

Highlighted text

Live Editor
  • Use descriptive class names
  • Avoid overly generic names

HTML Id

The id attribute uniquely identifies an element on a page.

  • Must be unique
  • Used for anchors and scripting
  • Has higher CSS specificity

Ids are useful for linking to specific sections or applying unique styles.

Syntax

<div id="header"></div>
Example

Section 1

Live Editor
  • Use ids sparingly
  • Keep names meaningful

HTML Buttons

Buttons allow users to trigger actions such as submitting forms or running scripts.

  • Interactive element
  • Works with JavaScript
  • Supports different types

Buttons can perform navigation, submit forms, or trigger events.

Syntax

<button>Click</button>
Example


    
Live Editor
  • Always define button type in forms
  • Use clear action labels

HTML Iframes

Iframes embed another webpage or content within your page.

  • Useful for embedding external content
  • Can display videos, maps, or pages
  • Supports sandbox security

Iframes are commonly used to embed third-party content safely.

Syntax

<iframe src="url"></iframe>
Example


    
Live Editor
  • Use sandbox for security
  • Avoid embedding untrusted sources

HTML JavaScript

JavaScript makes HTML pages dynamic and interactive. You can embed scripts directly in HTML using the <script> tag, or link to an external JavaScript file.

  • Add scripts using the <script> tag
  • JavaScript can be inline or in an external file
  • Manipulates HTML using the DOM
  • Can respond to user events like clicks and input

JavaScript runs in the browser and can modify page content, handle user actions, and communicate with servers. Best practice is to place scripts at the bottom of the page or use the defer attribute.

Syntax

<script> // JavaScript code here </script>
Example

<button onclick="showMessage()">Click Me</button>

<script>
  function showMessage() {
    alert("Hello from JavaScript!");
  }
</script>
    
Live Editor

Example Explained

  • onclick — Event attribute that runs JavaScript when the button is clicked
  • <script> — Defines a block of JavaScript code
  • alert() — Displays a message dialog in the browser
  • Use external JS files for larger projects
  • Avoid inline scripts for better maintainability
  • Use the defer attribute for better page load performance

HTML File Paths

File paths specify the location of resources like images, stylesheets, scripts, and other files relative to the current document or as absolute URLs.

  • Absolute paths use full URLs (start with https:// or /)
  • Relative paths are based on current file location
  • Correct paths prevent broken images and missing resources

Using relative paths keeps projects portable across different environments and servers.

Path Types

Path Description
images/photo.jpg Relative — same folder
../images/photo.jpg Relative — one folder up
/images/photo.jpg Absolute from root
https://example.com/img.jpg Full absolute URL

Syntax

<img src="images/photo.jpg" alt="description">
Example

<img src="https://via.placeholder.com/150" alt="Sample">
<a href="../index.html">Go to Home</a>
    
Live Editor
  • Use relative paths for internal files
  • Check all paths when deploying to a server
  • Keep your folder structure organized and consistent

HTML Head

The <head> element contains metadata and resources that define how a page behaves and appears.

  • Contains meta tags, title, styles, and scripts
  • Not visible on the page
  • Important for SEO and performance

Proper use of the head improves search engine ranking, accessibility, and page loading speed.

Syntax

<head> ... </head>
Example


  My Page
  

    
Live Editor
  • Always include charset meta tag
  • Keep scripts deferred
  • Add meta description for SEO

HTML Layout

Layout elements define the structure of a web page using semantic tags.

  • Use header, nav, main, section, footer
  • Improves accessibility
  • Helps search engines understand content

Modern layouts rely on semantic structure combined with CSS Flexbox or Grid for positioning.

Syntax

<header>...</header>
Example

Header
Main Content
Footer
Live Editor
  • Use semantic tags instead of generic divs
  • Keep layout consistent across pages
  • Combine with CSS Grid for responsiveness

HTML Responsive

Responsive design ensures your website looks good on all screen sizes.

  • Use viewport meta tag
  • Flexible layouts with CSS
  • Responsive images

Modern websites must adapt to phones, tablets, and desktops. HTML works with CSS media queries to achieve responsiveness.

Syntax

<meta name="viewport" content="width=device-width, initial-scale=1.0">
Example


    
Live Editor
  • Always include viewport meta tag
  • Use flexible units like % or rem
  • Test on multiple devices

HTML Semantics

Semantic HTML uses meaningful tags that clearly describe the purpose of content, improving accessibility, SEO, and code readability.

  • Semantic tags describe content meaning
  • Improves accessibility for screen readers
  • Helps search engines understand structure

Instead of relying only on generic containers, semantic elements like <article>, <section>, and <nav> provide context about what each part of the page represents.

Using semantic markup makes projects easier to maintain and aligns with modern HTML5 standards.

Syntax

<article>Content</article>
Example

Blog Post

This is a semantic article element.

Live Editor
  • Prefer semantic elements over generic divs
  • Use <main> only once per page
  • Structure content logically

HTML Computer Code

HTML contains several elements for defining user input and computer code.

  • <code> for computer code
  • <kbd> for keyboard input
  • <samp> for computer output
  • <var> for variables
  • <pre> for preformatted text

These elements are used to display code snippets, keyboard shortcuts, and technical documentation clearly.

Syntax

<code>x = 5;</code>
Example

x = 5; y = 6; z = x + y;
    
Live Editor
  • Use <pre> to preserve whitespace
  • Combine <pre> and <code> for multi-line blocks

HTML Semantics

Semantic HTML uses meaningful tags that clearly describe the purpose of content, improving accessibility, SEO, and code readability.

  • Semantic tags describe content meaning
  • Improves accessibility for screen readers
  • Helps search engines understand structure

Instead of relying only on generic containers, semantic elements like <article>, <section>, and <nav> provide context about what each part of the page represents.

Syntax

<article>Content</article>
Example

Blog Post

This is a semantic article element.

Live Editor
  • Prefer semantic elements over generic divs
  • Use <main> only once per page

HTML Style Guide

A style guide ensures consistent and readable HTML across projects, making collaboration easier and reducing errors.

  • Use lowercase tag names
  • Indent nested elements
  • Close all elements properly

Consistent formatting helps developers quickly understand code. Teams often define their own style rules, but following common conventions improves maintainability.

Modern best practices also emphasize semantic structure and accessibility.

Syntax

<element attribute="value">
Example



  
    Styled HTML
  
  
    

Consistent Formatting

Live Editor
  • Keep lines short and readable
  • Use meaningful class names
  • Validate HTML regularly

HTML Entities

Entities are used to display reserved characters or symbols that cannot be typed directly in HTML.

  • Begin with & and end with ;
  • Used for reserved characters
  • Ensure correct rendering

For example, the less-than symbol cannot be written directly because it would be interpreted as a tag. Entities solve this by encoding characters.

Syntax

&entityName;
Example

5 < 10

Copyright © 2026

Live Editor
  • Use entities for reserved characters
  • Prefer UTF-8 charset for wider support
  • Memorize common entities like &nbsp;

HTML Symbols

HTML supports a wide range of mathematical, currency, and technical symbols using entities or Unicode.

  • Useful for technical content
  • Rendered using entity codes
  • Supported across modern browsers

Symbols are commonly used in finance, engineering, and documentation pages.

Syntax

&#symbolCode;
Example

€ Euro

☃ Snowman

Live Editor
  • Check symbol compatibility
  • Use UTF-8 charset
  • Test across devices

HTML Emojis

Emojis can be added using Unicode characters, making interfaces more expressive and user-friendly.

  • Use Unicode codes
  • Requires UTF-8 charset
  • Supported in modern browsers

Emojis are widely used in messaging interfaces, notifications, and social platforms.

Syntax

&#128512;
Example

😀 Smile Emoji

🚀 Rocket Emoji

Live Editor
  • Use emojis sparingly in professional sites
  • Ensure accessibility with text labels
  • Test rendering across platforms

HTML Charsets

A character set defines how text is stored and displayed in a web page. UTF-8 is the standard charset because it supports almost all characters and symbols.

  • UTF-8 is the recommended charset
  • Ensures correct display of international text
  • Must be declared in the head

Without a proper charset, browsers may display garbled text. UTF-8 allows you to safely include emojis, symbols, and multilingual content.

Syntax

<meta charset="UTF-8">
Example


  

    
Live Editor
  • Always use UTF-8
  • Place charset early in the head
  • Avoid mixing encodings

HTML URL Encoding

URL encoding converts characters into a format that can be safely transmitted over the internet.

  • Spaces become %20
  • Special characters are encoded
  • Ensures valid URLs

Encoding prevents errors when URLs contain spaces, symbols, or non-ASCII text. Browsers often handle encoding automatically, but developers should understand how it works.

Syntax

https://example.com/search?q=web%20design
Example

Search
    
Live Editor
  • Encode query parameters
  • Avoid spaces in URLs
  • Use built-in encoding functions in JS

HTML vs XHTML

XHTML is a stricter, XML-based version of HTML. Modern development mainly uses HTML5, but understanding XHTML helps you write cleaner code.

  • XHTML requires proper closing tags
  • HTML is more flexible
  • HTML5 is the current standard

XHTML enforced strict syntax rules like lowercase tags and well-formed structure. HTML5 adopted many of these best practices while remaining developer-friendly.

Syntax

<br /> (XHTML) vs <br> (HTML)
Example

HTML allows flexible syntax.


XHTML requires self-closing tags.


Live Editor
  • Follow XHTML discipline for cleaner HTML
  • Always close elements
  • Use HTML5 for modern projects

HTML Forms

Forms allow users to send data to a server. They are essential for login pages, registrations, searches, and feedback systems.

  • Collect user input
  • Use input, textarea, and select
  • Submit data using HTTP methods

The form element acts as a container for different input controls. Each control collects specific data that is sent to a server when the form is submitted.

Forms are a core part of interactive web applications.

Syntax

<form action="/submit" method="post"></form>
Example

Live Editor
  • Always include labels
  • Validate inputs
  • Use appropriate input types

HTML Form Attributes

Form attributes control how and where form data is sent when a user submits a form.

  • action defines submission URL
  • method sets HTTP method
  • target controls response location

Choosing the right attributes ensures data is handled securely and correctly. Most forms use the POST method when sending sensitive data.

Syntax

<form action="/submit" method="post">
Example

Live Editor
  • Use POST for sensitive data
  • Validate on client and server
  • Always define an action

HTML Form Elements

Form elements are controls that allow users to enter and select data.

  • Common elements include input, textarea, select
  • Buttons trigger form actions
  • Labels improve accessibility

Each element serves a specific purpose. Combining them creates complete forms such as registration or contact forms.

Syntax

<input> <textarea> <select>
Example

Live Editor
  • Group related inputs
  • Use labels for usability
  • Keep forms simple

HTML Input Types

Input types define the kind of data users can enter, such as text, email, date, or password.

  • Different types provide built-in validation
  • Improve mobile user experience
  • Ensure accurate data entry

Using appropriate input types helps browsers display the right keyboard on mobile devices and reduces validation errors.

Syntax

<input type="email">
Example




    
Live Editor
  • Use semantic input types
  • Avoid using text for everything
  • Combine with validation attributes

HTML Input Attributes

Input attributes provide additional control over form fields such as validation rules and default values.

  • placeholder shows hint text
  • required enforces validation
  • value sets default content

Attributes help guide users and ensure the correct data format is submitted.

Syntax

<input type="text" required>
Example



    
Live Editor
  • Use required for important fields
  • Provide helpful placeholders
  • Combine validation attributes

HTML Form Validation

HTML provides built-in validation features that help ensure users enter the correct type of data before submitting a form.

  • Reduces invalid submissions
  • Improves user experience
  • No JavaScript required for basic checks

Validation attributes like required, pattern, and minlength allow developers to enforce rules directly in HTML.

Syntax

<input type="email" required>
Example

Live Editor
  • Use validation alongside server checks
  • Provide clear error messages
  • Test validation on mobile devices

HTML Fieldset & Legend

The fieldset element groups related form controls, while legend provides a caption for the group.

  • Improves accessibility
  • Organizes long forms
  • Provides context to users

Using fieldsets makes forms easier to understand, especially when they contain multiple sections like billing and shipping information.

Syntax

<fieldset><legend>Info</legend></fieldset>
Example

Contact Info
Live Editor
  • Use for multi-section forms
  • Keep legends descriptive
  • Avoid over-nesting fieldsets

HTML Datalist

The datalist element provides autocomplete suggestions for input fields.

  • Enhances usability
  • Allows custom suggestions
  • Works with input list attribute

Datalists are useful for suggesting common values like cities or product names while still allowing custom input.

Syntax

<input list="items">
Example



  
    
Live Editor
  • Use for suggestions, not restrictions
  • Provide common options
  • Ensure accessibility labels

HTML Canvas

The canvas element allows you to draw graphics dynamically using JavaScript.

  • Used for games and visualizations
  • Requires JavaScript
  • Pixel-based rendering

Canvas is commonly used for charts, animations, and interactive graphics.

Syntax

<canvas id="myCanvas"></canvas>
Example



    
Live Editor
  • Always set canvas width and height
  • Use for dynamic visuals
  • Prefer SVG for scalable graphics

HTML SVG

SVG (Scalable Vector Graphics) is used to create resolution-independent graphics directly in HTML.

  • Vector-based graphics
  • Scales without losing quality
  • Styled with CSS

SVG is ideal for icons, charts, and illustrations because it remains sharp at any size.

Syntax

<svg><circle /></svg>
Example


  

    
Live Editor
  • Use SVG for logos and icons
  • Inline SVG allows CSS styling
  • Optimize SVG for performance

HTML Graphics

HTML supports two powerful technologies for creating graphics on the web: Canvas (pixel-based, JavaScript-driven) and SVG (vector-based, scalable).

  • Canvas is used for dynamic, pixel-level drawing
  • SVG uses XML-based shapes and scales without quality loss
  • Both are natively supported in all modern browsers

Choose Canvas for animations and games; choose SVG for icons, logos, and illustrations that need to be sharp at any size.

  • Use SVG for static graphics and icons
  • Use Canvas for real-time animated visuals
  • Both can be styled with CSS and scripted with JavaScript

HTML Media

HTML5 introduced native support for embedding audio and video directly in web pages without needing plugins like Flash.

  • Use <video> for video content
  • Use <audio> for sound and music
  • Multiple <source> elements provide format fallbacks
  • Supports playback controls, autoplay, and loop

Media elements are widely supported and provide a seamless, accessible way to include rich content in your pages.

  • Always provide alternative text or fallback content
  • Compress media files for faster loading
  • Use preload="metadata" to improve performance

HTML Video

The <video> element embeds video content directly into a webpage with built-in browser controls.

  • Supports MP4, WebM, and Ogg formats
  • Use controls to add play/pause UI
  • Supports autoplay, loop, and muted

Syntax

<video src="file.mp4" controls></video>
Example

<video width="400" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>
            
Live Editor
  • Always include a fallback message inside the tag
  • Use muted with autoplay for browser compatibility

HTML Audio

The <audio> element embeds sound content such as music or podcasts directly into webpages.

  • Supports MP3, WAV, and Ogg formats
  • Use controls attribute for playback UI
  • Can loop, autoplay, and be muted

Syntax

<audio controls><source src="file.mp3"></audio>
Example

<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
  Your browser does not support the audio element.
</audio>
            
Live Editor
  • Always provide fallback text for old browsers
  • Use multiple <source> elements for browser compatibility

HTML Plug-ins

The <object> and <embed> elements were historically used to embed external content like PDFs, Flash, or Java applets. Today, native HTML5 elements are preferred.

  • <object> embeds external resources
  • <embed> is a self-closing void element
  • Flash is no longer supported — use HTML5 alternatives

Syntax

<object data="file.pdf" type="application/pdf"></object>
Example

<object data="document.pdf" type="application/pdf" width="500" height="400">
  <p>Your browser does not support PDFs. <a href="document.pdf">Download the PDF</a></p>
</object>
            
Live Editor
  • Prefer native HTML5 elements over <object>
  • Always provide fallback content

HTML YouTube

The easiest way to embed a YouTube video is using an <iframe> with the YouTube embed URL.

  • Use YouTube's embed URL format
  • Control playback with URL parameters
  • Add allowfullscreen for fullscreen support

Syntax

<iframe src="https://www.youtube.com/embed/VIDEO_ID"></iframe>
Example

<iframe width="560" height="315"
  src="https://www.youtube.com/embed/dQw4w9WgXcQ"
  allowfullscreen>
</iframe>
            
Live Editor
  • Add ?rel=0 to prevent showing unrelated videos
  • Use ?mute=1 for autoplay compliance

HTML Web APIs

HTML5 introduced several powerful browser APIs that allow JavaScript to access device features and browser capabilities directly.

  • Geolocation — access user's GPS coordinates
  • Drag & Drop — move elements with the mouse
  • Web Storage — store data in the browser
  • Web Workers — run scripts in background threads
  • Server-Sent Events — receive real-time updates from server

These APIs make it possible to build rich, app-like experiences entirely in the browser without plugins.

  • Always check browser compatibility before using newer APIs
  • Request only permissions you need (e.g., Geolocation)

HTML Geolocation

The Geolocation API allows you to get the user's current geographic location with their permission.

  • Uses navigator.geolocation
  • Returns latitude and longitude coordinates
  • Requires HTTPS and user permission

Syntax

navigator.geolocation.getCurrentPosition(successFn);
Example

<button onclick="getLocation()">Get My Location</button>
<p id="demo"></p>

<script>
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    document.getElementById("demo").innerHTML = "Geolocation not supported.";
  }
}
function showPosition(position) {
  document.getElementById("demo").innerHTML =
    "Lat: " + position.coords.latitude +
    "<br>Lon: " + position.coords.longitude;
}
</script>
            
Live Editor
  • Only works over HTTPS in production
  • Always handle error cases gracefully

HTML Drag & Drop

The HTML Drag and Drop API enables elements to be dragged and dropped using mouse or touch events.

  • Use draggable="true" on source element
  • Handle ondragstart, ondrop, and ondragover events
  • Use event.dataTransfer to pass data

Syntax

<div draggable="true" ondragstart="drag(event)">Drag me</div>
Example

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="img.png" draggable="true" ondragstart="drag(event)">

<script>
function allowDrop(ev) { ev.preventDefault(); }
function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); }
function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
            
Live Editor
  • Call event.preventDefault() in ondragover to allow dropping
  • Use dataTransfer to pass data between drag source and drop target

HTML Web Storage

Web Storage allows web applications to store data locally in the user's browser — more securely and with larger capacity than cookies.

  • localStorage — persists even after browser close
  • sessionStorage — cleared when tab closes
  • Both store key-value string pairs
  • Up to ~5-10MB storage per origin

Syntax

localStorage.setItem("key", "value");
localStorage.getItem("key");
Example

<button onclick="saveData()">Save</button>
<button onclick="loadData()">Load</button>
<p id="result"></p>

<script>
function saveData() {
  localStorage.setItem("username", "LearnX User");
  alert("Saved!");
}
function loadData() {
  var name = localStorage.getItem("username") || "No data found";
  document.getElementById("result").innerText = name;
}
</script>
            
Live Editor
  • Never store sensitive data (passwords, tokens) in localStorage
  • Use JSON.stringify() to store objects

HTML Web Workers

Web Workers let you run JavaScript in a background thread, keeping the main UI thread free and responsive.

  • Run scripts in the background
  • Cannot access the DOM directly
  • Communicate with main thread via postMessage()
  • Ideal for CPU-heavy tasks

Syntax

const worker = new Worker("worker.js");
worker.postMessage("start");
worker.onmessage = (e) => console.log(e.data);
Example — Concept

<!-- main.html -->
<button onclick="startWorker()">Start Worker</button>
<p id="result"></p>

<script>
let w;
function startWorker() {
  if (typeof(Worker) !== "undefined") {
    w = new Worker("worker.js");
    w.onmessage = (e) => {
      document.getElementById("result").innerText = e.data;
    };
  }
}
</script>

<!-- worker.js file -->
<!-- postMessage("Worker is running!"); -->
            
  • Worker scripts must be in separate files
  • Great for sorting large arrays or processing data
  • Always terminate workers when done: worker.terminate()

HTML Server-Sent Events (SSE)

Server-Sent Events allow a server to push real-time updates to the browser over a persistent HTTP connection.

  • One-way: server → client
  • Uses the EventSource API
  • Automatic reconnection on disconnect
  • Requires a server endpoint that sends text/event-stream

Syntax

const source = new EventSource("/stream");
source.onmessage = (e) => console.log(e.data);
Example — Concept

<!-- Client-side -->
<div id="updates"></div>
<script>
const source = new EventSource("/sse-endpoint");
source.onmessage = function(e) {
  document.getElementById("updates").innerHTML += e.data + "<br>";
};
</script>

<!-- Server-side (Node.js example) -->
<!-- res.setHeader("Content-Type","text/event-stream"); -->
<!-- res.write("data: Hello World\n\n"); -->
            
  • SSE is simpler than WebSockets for one-way updates
  • Ideal for notifications, live feeds, and dashboards
  • Not supported in Internet Explorer

HTML Quiz

Test your HTML knowledge with these questions! Try to answer each one before revealing the answer.

  • Q1: What does HTML stand for?
  • Q2: Which tag creates the largest heading?
  • Q3: Which attribute is used to specify alternate text for an image?
  • Q4: Which HTML element defines the document's body?
  • Q5: How do you create a hyperlink in HTML?
  • A1: HyperText Markup Language
  • A2: <h1>
  • A3: The alt attribute
  • A4: <body>
  • A5: <a href="url">Link text</a>

HTML Exercises

Practice makes perfect! Try these hands-on exercises to reinforce your HTML skills.

  • Exercise 1: Create a page with a heading and 2 paragraphs
  • Exercise 2: Build an ordered list of your 5 favorite movies
  • Exercise 3: Create a table with 3 columns and 3 rows
  • Exercise 4: Build a contact form with name, email, and message
  • Exercise 5: Create a page that uses header, main, and footer
Exercise 1 — Starter

<!DOCTYPE html>
<html>
<head>
  <title>Exercise Page</title>
</head>
<body>
  <h1>My Page Title</h1>
  <p>First paragraph goes here.</p>
  <p>Second paragraph goes here.</p>
</body>
</html>
            
Live Editor

HTML Accessibility

Accessible HTML ensures that your website can be used by everyone, including people with visual, auditory, motor, or cognitive disabilities.

  • Use semantic HTML elements (header, nav, main, article, aside, footer)
  • Always add alt text to images
  • Use <label> for form inputs
  • Ensure keyboard navigation works
  • Use ARIA attributes where needed
  • Maintain good color contrast (WCAG guidelines)

ARIA Attributes

ARIA (Accessible Rich Internet Applications) attributes add accessibility information to HTML elements:

Example

<!-- Button with ARIA label -->
<button aria-label="Close menu">×</button>

<!-- Navigation with role -->
<nav aria-label="Main navigation">
  <a href="#home">Home</a>
</nav>

<!-- Image with descriptive alt -->
<img src="chart.png" alt="Sales growth chart showing 40% increase in Q3 2025">

<!-- Accessible form -->
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>
            
Live Editor
  • Test with a screen reader (NVDA, VoiceOver)
  • Use the WAVE accessibility tool
  • Follow WCAG 2.1 AA standards as a minimum

HTML Summary

You have now covered all the major HTML topics. Here's a quick recap of the most important concepts:

  • HTML is the standard markup language for creating web pages
  • HTML elements are represented by tags like <p>, <h1>, <div>
  • Always start with <!DOCTYPE html>
  • Use semantic elements: header, nav, main, section, article, footer
  • Forms collect user input with various input types
  • Media elements embed video and audio natively
  • APIs like Geolocation and Web Storage extend browser capabilities
  • Accessibility ensures your site works for all users

What's Next?

Now that you know HTML, the natural progression is:

  1. CSS — Style your HTML pages with colors, fonts, and layouts
  2. JavaScript — Add interactivity and dynamic behavior
  3. A Framework (React, Vue) — Build modern web applications
  • Practice by building real projects
  • Read the MDN Web Docs for detailed references
  • Validate your HTML at validator.w3.org

HTML Tag List

A reference of the most commonly used HTML tags and their purpose:

Tag Description
<!DOCTYPE> Defines the document type
<html> Root element of an HTML page
<head> Contains metadata/information for the document
<title> Defines the page title (shown in browser tab)
<body> Defines the document's body
<h1>–<h6> Defines HTML headings
<p> Defines a paragraph
<a> Defines a hyperlink
<img> Defines an image
<ul> / <ol> Unordered / Ordered list
<li> Defines a list item
<table> Defines a table
<form> Defines an HTML form
<input> Defines an input control
<button> Defines a clickable button
<div> Defines a section/container (block)
<span> Defines an inline container
<header> Semantic header element
<nav> Defines navigation links
<main> Specifies the main content
<section> Defines a section in a document
<article> Defines self-contained content
<aside> Defines content aside from main content
<footer> Semantic footer element
<strong> Bold text with semantic importance
<em> Italic text with semantic emphasis
<br> Inserts a single line break
<hr> Defines a thematic change/horizontal rule
<canvas> Used to draw graphics via JavaScript
<video> Defines video or movie content
<audio> Defines sound content
<iframe> Defines an inline frame
<script> Defines a client-side script
<link> Links external resources (CSS, icons)
<meta> Defines metadata about the document