HTML 31 ๐ป 1-29 Full ๐ป
1. Introduction to HTML
HTML, which stands for Hyper Text Markup Language, is the standard markup language used to create web pages. It consists of a series of elements that tell the browser how to display content.
Setting Up Your Development Environment
To start coding in HTML, you’ll need a code editor. We recommend using Visual Studio Code (VS Code).
- Download VS Code: Visit the official download page at https://code.visualstudio.com/download and install the version suitable for your operating system.
Your First “Hello World” Page
Once VS Code is installed, follow these steps:
- Create a new file and save it with the
.htmlextension (e.g.,index.html). - In the file, type
html5and press Tab (or Enter) โ VS Code will automatically generate a basic HTML5 template for you.
Your template will look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
Running Your HTML File
There are two simple ways to view your HTML file in a browser:
- Using Live Server (recommended): Install the “Live Server” extension in VS Code. Right-click on your HTML file and select “Open with Live Server” โ this will launch your page in the browser and automatically refresh whenever you make changes.
- Directly: You can also double-click the HTML file to open it directly in your web browser.
Understanding the HTML Structure
Here’s a breakdown of the key components in a typical HTML document:
| Element | Description |
|---|---|
<!DOCTYPE html> | Declares the document type and version โ this tells the browser it’s an HTML5 document. |
<html> | The root element that wraps all the content on the page. |
<head> | Contains metadata (data about the data), such as character set, styles, and scripts. |
<title> | Sets the title of the webpage, which appears in the browser’s title bar or tab. |
<body> | Holds all the visible content of the webpage โ text, images, links, etc. |
<h1> | Defines the largest heading โ used for main titles and important headings. |
This foundation will help you understand how HTML works and how to start building your own web pages. Happy coding! ๐
2. Elements
An element is the building block of an HTML page. It typically consists of an opening tag, attributes, content, and a closing tag.
Basic Structure of an Element
<h1>Hello World</h1>
<h1>โ opening tagHello Worldโ content</h1>โ closing tag
Important Rules to Remember
- Always close your elements โ forgetting the closing tag can break your page layout.
<h2>This is correct</h2>
- Elements can contain other elements โ this is called nesting. For example, the
<body>element contains all visible content:
<body>
<h1>Welcome</h1>
<p>This is a paragraph.</p>
</body>
- Empty elements have no content โ they are written with a self-closing tag or just an opening tag:
<h1></h1> <!-- Empty heading -->
<br> <!-- Line break (self-closing) -->
- W3C recommends using lowercase for all HTML tags and attributes for better readability and consistency.
Element Attributes
Attributes provide additional information about an element. They are always written inside the opening tag and are optional.
An attribute consists of a name and a value:
<tagname attribute="value">Content</tagname>
Example:
<h1 id="main-title" class="header">Welcome to My Site</h1>
The 4 Categories of Attributes
| Category | Description | Example |
|---|---|---|
| Universal (Global) Attributes | Can be used on almost all HTML elements | id, class, style, title |
| Specific Attributes | Only work on specific elements | src (for <img>), href (for <a>) |
| Event Attributes | Trigger actions when events occur (click, hover, etc.) | onclick, onmouseover |
| Data Attributes | Store custom information for use in scripts | data-user="John" |
Universal (Global) Attributes Explained
These attributes can be applied to nearly every HTML element:
| Attribute | Purpose | Example |
|---|---|---|
id | Uniquely identifies an element (must be unique on the page) | id="header" |
class | Assigns one or more class names to an element (used for styling or scripting) | class="button primary" |
style | Defines inline CSS styles directly on the element | style="color: blue; font-size: 2em" |
title | Displays a tooltip when the user hovers over the element | title="Click here for more info" |
lang | Specifies the language of the element’s content | <html lang="en"> |
dir | Defines the text direction โ ltr (left-to-right) or rtl (right-to-left) | dir="rtl" |
Quick Example Using Multiple Attributes
<h1 id="main-heading" class="title large" style="color: navy;" title="This is the main title" lang="en" dir="ltr">
Welcome to HTML
</h1>
This foundation in elements and attributes will help you build well-structured, interactive, and styled web pages. ๐
3. Headings
Headings are essential for structuring your web content. They create a clear hierarchy that helps both users and search engines understand the organization of your page.
All Heading Levels
HTML provides six levels of headings, from <h1> (most important) to <h6> (least important):
<h1>Level 1 Heading</h1>
<h2>Level 2 Heading</h2>
<h3>Level 3 Heading</h3>
<h4>Level 4 Heading</h4>
<h5>Level 5 Heading</h5>
<h6>Level 6 Heading</h6>
Key Rules for Using Headings
| Rule | Explanation |
|---|---|
Start with <h1> | Always begin your page with a single <h1> that describes the main content. |
| Don’t skip levels | Follow <h1> with <h2>, then <h3>, and so on โ never jump from <h1> to <h3>. |
Use only one <h1> per page | While technically allowed, multiple <h1> elements are not considered a best practice. |
| Don’t use headings to resize text | Headings are for structure, not styling. Use CSS font-size for visual adjustments. |
| Use headings to build a table of contents | User agents (like screen readers) can automatically generate a document outline from your headings. |
How Headings Create Structure
Think of headings like the outline of a book chapter:
<h1>Introduction to HTML</h1>
<h2>What is HTML?</h2>
<h3>Brief History</h3>
<h3>Why Learn HTML?</h3>
<h2>Getting Started</h2>
<h3>Setting Up Your Editor</h3>
<h3>Your First Page</h3>
This structure would generate a clear outline:
- Introduction to HTML
- What is HTML?
- Brief History
- Why Learn HTML?
- Getting Started
- Setting Up Your Editor
- Your First Page
Real-World Example: This Could Be a Book’s Contents
Here’s how you might structure a travel guide using headings:
<h1>Ultimate Travel Guide to Japan</h1>
<h2>1. Planning Your Trip</h2>
<h3>Best Time to Visit</h3>
<h3>Budget Planning</h3>
<h3>Visa Requirements</h3>
<h2>2. Top Destinations</h2>
<h3>Tokyo</h3>
<h4>Shinjuku</h4>
<h4>Shibuya</h4>
<h3>Kyoto</h3>
<h4>Fushimi Inari Shrine</h4>
<h4>Kinkaku-ji Temple</h4>
<h2>3. Food & Culture</h2>
<h3>Must-Try Dishes</h3>
<h3>Cultural Etiquette</h3>
Accessibility Tips
Screen reader users often navigate pages by jumping between headings. Following best practices ensures your content is accessible:
โ Do this:
<h1>Main Title</h1>
<h2>Section Title</h2>
<h3>Subsection Title</h3>
โ Don’t do this (skipping levels):
<h1>Main Title</h1>
<h3>Section Title</h3> <!-- Oops! Skipped <h2> -->
Quick Reference
| Element | Use For | Example |
|---|---|---|
<h1> | Main page title (once per page) | <h1>My Website</h1> |
<h2> | Major sections | <h2>About Me</h2> |
<h3> | Subsections under <h2> | <h3>My Skills</h3> |
<h4> | Subsections under <h3> | <h4>Technical Skills</h4> |
<h5> | Minor subsections | <h5>JavaScript</h5> |
<h6> | Least important heading | <h6>Notes</h6> |
For more in-depth information, check out the MDN Web Docs on Heading Elements.
4. Paragraph, Preformatted Text, and Line Break
Now let’s add some content to our page structure. We’ll use paragraphs, line breaks, and preformatted text to control how text is displayed.
The Paragraph Element <p>
The <p> element represents a paragraph of text. It automatically starts on a new line with a small space above it.
<h1>Welcome to My Website</h1>
<h2>About This Site</h2>
<p>This is a paragraph of text. It will start on a new line and have some spacing above it.</p>
<p>This is another paragraph. Notice the space between paragraphs.</p>
Key Points About Paragraphs:
- Browsers automatically remove extra spaces and line breaks inside a
<p>element - Multiple spaces are collapsed into a single space
- Line breaks in your HTML code do not create line breaks in the browser
Example of Space Collapsing:
<p>This text has many spaces.</p>
<!-- Browser displays: "This text has many spaces." -->
<p>This text
is written on
multiple lines
in the code.</p>
<!-- Browser displays: "This text is written on multiple lines in the code." -->
The Line Break Element <br>
To force a line break within a paragraph, use the <br> element (a self-closing tag).
<p>
This is the first line.<br>
This is the second line.<br>
This is the third line.
</p>
Browser Display:
This is the first line.
This is the second line.
This is the third line.
Note: <br> is an empty element โ it has no content and no closing tag.
The Preformatted Text Element <pre>
The <pre> element displays text exactly as it is written in the HTML file โ preserving all spaces, line breaks, and formatting.
<h2>Using the Pre Element</h2>
<pre>
This text keeps all spaces.
It also preserves line breaks.
Even blank lines are shown!
</pre>
Browser Display:
This text keeps all spaces.
It also preserves line breaks.
Even blank lines are shown!
When to Use <pre>:
- Displaying code snippets
- Showing ASCII art
- Preserving formatted text like poetry
- Any text where spacing and line breaks matter
Complete Example Using All Three Elements
Here’s a complete example showing headings, paragraphs, line breaks, and preformatted text together:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Formatting Examples</title>
</head>
<body>
<h1>Text Formatting Guide</h1>
<h2>1. Paragraphs</h2>
<p>This is a normal paragraph. All extra spaces and line breaks are ignored by the browser.</p>
<p>This is another paragraph. Notice the automatic spacing between paragraphs.</p>
<h2>2. Line Breaks</h2>
<p>
This line ends with a break.<br>
This text starts on a new line.<br>
You can use multiple breaks for extra spacing.<br><br>
This text has two breaks before it.
</p>
<h2>3. Preformatted Text</h2>
<p>Here's how the same text looks inside a pre element:</p>
<pre>
This line has multiple spaces.
This is on a new line.
This line is indented.
And this preserves the exact format.
</pre>
<h2>4. Comparison</h2>
<h3>Using a Paragraph:</h3>
<p>
This text has extra spaces.
It is written on multiple lines.
The browser collapses everything.
</p>
<h3>Using Preformatted Text:</h3>
<pre>
This text has extra spaces.
It is written on multiple lines.
The browser preserves everything!
</pre>
</body>
</html>
Quick Reference
| Element | Purpose | Preserves Spaces? | Preserves Line Breaks? |
|---|---|---|---|
<p> | Regular paragraph | โ No | โ No |
<br> | Single line break | N/A | โ Yes (adds one) |
<pre> | Preformatted text | โ Yes | โ Yes |
Pro Tip: Use paragraphs for regular content, line breaks for visual spacing within text, and preformatted text when you need to display code or other formatted content exactly as typed.
6. del, ins, sub, sup Elements
These elements are used for showing document changes and displaying specialized text formatting like subscripts and superscripts.
The Deleted Element <del>
The <del> element represents text that has been deleted from a document, typically shown with a strikethrough.
<del datetime="2024-05-05T00:00:00Z">This was deleted</del>
Browser Display:This was deleted
Key Points:
- Used to highlight text that has been removed
- Shows document changes and revisions
- Styled with a strikethrough line by default
- datetime attribute: Specifies when the deletion occurred (uses ISO 8601 format)
The Inserted Element <ins>
The <ins> element represents text that has been added to a document, typically shown with an underline.
<p>This is the new <ins datetime="2024-05-05T00:00:00Z">inserted</ins> text that has been added.</p>
Browser Display:
This is the new inserted text that has been added.
Key Points:
- Used to highlight text that has been added
- Shows document changes and revisions
- Styled with an underline by default
- datetime attribute: Specifies when the insertion occurred (uses ISO 8601 format)
The Subscript Element <sub>
The <sub> element displays text as subscript โ it appears slightly below the normal line of text.
<p>The chemical formula for water is H<sub>2</sub>O.</p>
Browser Display:
The chemical formula for water is HโO.
Key Points:
- Text appears below the baseline
- Used for:
- Chemical formulas (HโO, COโ)
- Mathematical expressions (xโ, yโ)
- Footnotes in some contexts
- Often smaller in size than regular text
The Superscript Element <sup>
The <sup> element displays text as superscript โ it appears slightly above the normal line of text.
<p>The chemical formula for water contains two hydrogen atoms and one oxygen atom<sup>1</sup>.</p>
Browser Display:
The chemical formula for water contains two hydrogen atoms and one oxygen atomยน.
Key Points:
- Text appears above the baseline
- Used for:
- Mathematical exponents (xยฒ, yยณ)
- Ordinal numbers (1st, 2nd, 3rd)
- Footnotes and references
- Chemical formulas in some cases
- Often smaller in size than regular text
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>del, ins, sub, sup Elements</title>
</head>
<body>
<h1>Document Changes & Special Formatting</h1>
<h2>1. Deleted and Inserted Text</h2>
<h3>Original Version:</h3>
<p>The meeting will be held on <del datetime="2024-05-05T10:00:00Z">Monday, May 6th</del>.</p>
<h3>Updated Version:</h3>
<p>The meeting will be held on <ins datetime="2024-05-05T10:30:00Z">Wednesday, May 8th</ins>.</p>
<h3>Track Changes Example:</h3>
<p>
The <del>old system</del> <ins>new system</ins> will be implemented next week.
Please <del>ignore</del> <ins>review</ins> the updated guidelines.
</p>
<hr>
<h2>2. Subscript Examples</h2>
<h3>Chemical Formulas:</h3>
<ul>
<li>Water: H<sub>2</sub>O</li>
<li>Carbon Dioxide: CO<sub>2</sub></li>
<li>Glucose: C<sub>6</sub>H<sub>12</sub>O<sub>6</sub></li>
<li>Sulfuric Acid: H<sub>2</sub>SO<sub>4</sub></li>
</ul>
<h3>Mathematical Variables:</h3>
<p>
The coordinates are (x<sub>1</sub>, y<sub>1</sub>) and (x<sub>2</sub>, y<sub>2</sub>).
The sequence is a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ...
</p>
<hr>
<h2>3. Superscript Examples</h2>
<h3>Mathematical Exponents:</h3>
<ul>
<li>x<sup>2</sup> + y<sup>2</sup> = z<sup>2</sup></li>
<li>2<sup>10</sup> = 1024</li>
<li>E = mc<sup>2</sup></li>
</ul>
<h3>Ordinal Numbers:</h3>
<ul>
<li>1<sup>st</sup> Place</li>
<li>2<sup>nd</sup> Place</li>
<li>3<sup>rd</sup> Place</li>
<li>4<sup>th</sup> Place</li>
</ul>
<h3>Footnotes & References:</h3>
<p>
The study shows significant results<sup>1</sup>. This has been confirmed by multiple sources<sup>2,3</sup>.
</p>
<hr>
<h2>4. Combined Examples</h2>
<h3>Chemical Equation:</h3>
<p>
C<sub>6</sub>H<sub>12</sub>O<sub>6</sub> + 6O<sub>2</sub> โ 6CO<sub>2</sub> + 6H<sub>2</sub>O + Energy<sup>*</sup>
</p>
<h3>Document Revision:</h3>
<p>
<del datetime="2024-05-01T00:00:00Z">Version 1.0</del>
<ins datetime="2024-05-02T00:00:00Z">Version 1.1</ins>
<sup>[update]</sup>
</p>
</body>
</html>
Quick Reference
| Element | Purpose | Visual Style | Common Uses |
|---|---|---|---|
<del> | Deleted text | Strikethrough | Document revisions, tracked changes |
<ins> | Inserted text | Underline | Document revisions, tracked changes |
<sub> | Subscript | Below baseline | Chemical formulas, mathematical variables |
<sup> | Superscript | Above baseline | Exponents, ordinal numbers, footnotes |
Best Practices
โ Do This:
<!-- Use del and ins together for clear changes -->
<p>
The price was <del>$100</del> <ins>$80</ins>.
</p>
<!-- Use sub for chemical formulas -->
<p>H<sub>2</sub>O</p>
<!-- Use sup for exponents -->
<p>x<sup>2</sup> + y<sup>2</sup></p>
โ Don’t Do This:
<!-- Don't use del or ins just for visual styling -->
<p>This is <del>not actually deleted</del> but just styled.</p>
<!-- Use CSS text-decoration: line-through instead -->
<!-- Don't use sub/sup for footnotes when you want actual footnotes -->
<!-- Use proper footnote formatting with links -->
Pro Tip: Always include the datetime attribute when using <del> and <ins> to provide additional context about when changes were made. This is especially useful in collaborative documents and version histories.
7. blockquote, q, abbr, address, cite, bdo
These elements add semantic meaning to specific types of content like quotations, abbreviations, addresses, and text direction.
The Blockquote Element <blockquote>
The <blockquote> element represents a section of text that is quoted from another source. It creates a block-level quotation.
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</blockquote>
Browser Display:
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Key Points:
- Used for longer, block-level quotations
- Can contain one or more paragraphs
- May include other inline elements like
<em>,<strong>, or<code> - Often indented by default
- Can include a
citeattribute with the source URL
Example with Multiple Paragraphs:
<blockquote cite="https://example.com/source">
<p>This is the first paragraph of the quote.</p>
<p>This is the second paragraph of the same quote.</p>
<p><em>This paragraph contains emphasis</em> within the quote.</p>
</blockquote>
The Inline Quote Element <q>
The <q> element represents a short, inline quotation within a larger block of text.
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <q>In hac habitasse platea dictumst!</q></p>
Browser Display:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. “In hac habitasse platea dictumst!”
Key Points:
- Used for short, inline quotations
- Contains one or more words or sentences
- Browsers automatically add quotation marks
- More semantic than manually adding quote marks
Example:
<p>She said, <q>I'll be there in five minutes</q> before hanging up.</p>
The Abbreviation Element <abbr>
The <abbr> element defines an abbreviation or acronym, with the full form provided in the title attribute.
<p>The <abbr title="Academy Awards">Oscars</abbr> are presented annually by the Academy of Motion Picture Arts and Sciences.</p>
Browser Display:
The Oscars are presented annuallyโฆ
Key Points:
- Defines abbreviations and acronyms
- The
titleattribute provides the full explanation - Helps with accessibility and SEO
- Often displayed with a dotted underline
Examples:
<p>
The <abbr title="World Health Organization">WHO</abbr> recommends regular exercise.
HTML stands for <abbr title="Hyper Text Markup Language">HTML</abbr>.
Please send your <abbr title="Resume">CV</abbr> by Friday.
</p>
The Address Element <address>
The <address> element defines contact information for the nearest parent <article> or <body> element.
<p>The company's headquarters are located at:</p>
<address>
Somewhere in Europe
</address>
Browser Display:
Somewhere in Europe
Key Points:
- Defines contact information or an address
- Can contain address, email address, phone number, and other contact details
- Usually rendered in italic by default
- Used for the author or organization of the document
Better Examples:
<address>
<strong>John Doe</strong><br>
123 Main Street<br>
New York, NY 10001<br>
Email: <a href="mailto:john@example.com">john@example.com</a><br>
Phone: <a href="tel:+1234567890">(123) 456-7890</a>
</address>
The Citation Element <cite>
The <cite> element identifies the source of a quotation, reference, or block of text.
<p>According to <cite>Kronos</cite>, "Lorem ipsum dolor sit amet."</p>
Browser Display:
According to Kronos, “Lorem ipsum dolor sit amet.”
Key Points:
- Identifies the source of a quotation or reference
- Can contain a URL, book title, article title, page number, etc.
- Usually rendered in italic by default
- Provides attribution and credibility
Examples:
<p>
The concept of gravity was first described by <cite>Isaac Newton</cite>.
As <cite>The New York Times</cite> reported, the event was historic.
For more information, see <cite>Chapter 4, Page 78</cite>.
</p>
The BDO Element <bdo>
The <bdo> (Bi-Directional Override) element specifies the direction in which text should be displayed, overriding normal bidirectional formatting.
<bdo dir="rtl">
This text should be displayed in the right-to-left direction
</bdo>
Browser Display:This text should be displayed in the right-to-left direction (reversed)
Key Points:
- Used for texts in languages written right-to-left (Arabic, Hebrew)
- Overrides the normal bidirectional formatting rules
- Useful for documents with mixed text directions
- The
dirattribute specifies the direction:ltr(left-to-right) orrtl(right-to-left)
Examples:
<!-- Normal English text (left-to-right) -->
<p>Hello, this is English text.</p>
<!-- Right-to-left text -->
<bdo dir="rtl">Hello, this is reversed English text.</bdo>
<!-- Arabic text example -->
<p>Arabic is written <bdo dir="rtl">ู
ุฑุญุจุง ุจูู
</bdo> in the opposite direction.</p>
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quotations, Abbreviations, Addresses, Citations & BDO</title>
</head>
<body>
<h1>Quotations, Abbreviations, Addresses, Citations & BDO</h1>
<h2>1. Blockquote & Inline Quote</h2>
<h3>Blockquote:</h3>
<blockquote cite="https://example.com/philosophy">
<p>The unexamined life is not worth living.</p>
<p>This famous quote emphasizes the importance of self-reflection and philosophical inquiry.</p>
</blockquote>
<h3>Inline Quote:</h3>
<p>
As Socrates famously said, <q>I know that I know nothing</q>.
This paradox reminds us to remain humble in our pursuit of knowledge.
</p>
<hr>
<h2>2. Abbreviations</h2>
<p>
The <abbr title="National Aeronautics and Space Administration">NASA</abbr> was established in 1958.
The <abbr title="European Union">EU</abbr> has 27 member states.
Please submit your <abbr title="Frequently Asked Questions">FAQ</abbr> before the meeting.
</p>
<p>
HTML stands for <abbr title="Hyper Text Markup Language">HTML</abbr>,
while CSS stands for <abbr title="Cascading Style Sheets">CSS</abbr>.
</p>
<hr>
<h2>3. Address</h2>
<h3>Contact Information:</h3>
<address>
<strong>Tech Solutions Inc.</strong><br>
123 Innovation Drive<br>
Silicon Valley, CA 94043<br>
Email: <a href="mailto:info@techsolutions.com">info@techsolutions.com</a><br>
Phone: <a href="tel:+15551234567">(555) 123-4567</a>
</address>
<hr>
<h2>4. Citations</h2>
<p>
In <cite>To Kill a Mockingbird</cite>, Harper Lee writes about justice and morality.
According to <cite>Wikipedia</cite>, the first computer was invented in the 19th century.
For more details, see <cite>Chapter 3, Pages 45-50</cite>.
</p>
<blockquote cite="https://www.brainyquote.com/quotes/albert_einstein_100835">
<p>Imagination is more important than knowledge.</p>
<footer>โ <cite>Albert Einstein</cite></footer>
</blockquote>
<hr>
<h2>5. BDO - Text Direction</h2>
<h3>Left-to-Right (ltr):</h3>
<bdo dir="ltr">This text is displayed from left to right.</bdo>
<h3>Right-to-Left (rtl):</h3>
<bdo dir="rtl">This text is displayed from right to left.</bdo>
<h3>Practical Example:</h3>
<p>
English text mixed with Arabic:
<bdo dir="rtl">ู
ุฑุญุจุง ุจูู
</bdo> (Welcome in Arabic).
</p>
<hr>
<h2>6. Combined Example</h2>
<blockquote cite="https://example.com/interview">
<p>
The director explained, <q>This project represents a new direction for our company</q>,
as noted in <cite>Tech Weekly Magazine</cite>.
</p>
<footer>
โ <abbr title="Chief Executive Officer">CEO</abbr> at
<address>TechCorp, 500 Main St, New York, NY</address>
</footer>
</blockquote>
</body>
</html>
Quick Reference
| Element | Purpose | Visual Style | Common Uses |
|---|---|---|---|
<blockquote> | Block-level quote | Indented | Long quotations, testimonials |
<q> | Inline quote | Quotation marks | Short quotes within text |
<abbr> | Abbreviation | Dotted underline | Acronyms, shortened terms |
<address> | Contact information | Italic | Business addresses, author info |
<cite> | Citation source | Italic | Book titles, article references |
<bdo> | Text direction override | Normal text | Right-to-left languages |
Best Practices
โ Do This:
<!-- Use cite attribute with blockquote -->
<blockquote cite="https://source.com">
<p>Quoted text here.</p>
</blockquote>
<!-- Always provide title for abbreviations -->
<abbr title="World Wide Web">WWW</abbr>
<!-- Use address for actual contact info -->
<address>
Email: <a href="mailto:me@example.com">me@example.com</a>
</address>
โ Don’t Do This:
<!-- Don't use blockquote for indentation -->
<blockquote>This is just indented text</blockquote>
<!-- Use CSS margin or padding instead -->
<!-- Don't use cite for the author's name -->
<p>The author is <cite>John Smith</cite></p>
<!-- Use <span> or <strong> with CSS -->
<!-- Don't use address for fake or unrelated addresses -->
<address>Some random text that's not an address</address>
Pro Tip: Use blockquote and q together with the cite attribute to provide proper attribution. The <abbr> element is especially important for accessibility, as screen readers can announce the full meaning of abbreviations to users.
8. Comments and Anchor Element
Comments and hyperlinks are fundamental to creating well-documented and navigable web pages.
HTML Comments
Comments are used to add notes, explanations, or temporarily disable code without affecting the displayed content.
Syntax:
<!-- This is a comment -->
<p>This is some text</p>
<!--
<p>This text is commented out and will not display</p>
-->
Browser Display:
This is some text
Key Points:
- Comments are not displayed in the browser
- They improve code readability by explaining what different parts do
- Can be used to leave notes for yourself or other developers
- Temporarily disable code without deleting it
- Helpful for debugging and testing
Examples:
<!-- TODO: Add a navigation menu here -->
<!-- This section contains the main article -->
<article>
<h2>About Us</h2>
<p>Our company was founded in 2010...</p>
</article>
<!--
Multi-line comment explaining complex logic
This section handles user authentication
Last updated: January 2024
-->
<div class="login-form">
<!-- Login form content -->
</div>
The Anchor Element <a>
The <a> (anchor) element creates hyperlinks that allow users to navigate to other webpages, websites, or resources.
Basic Syntax:
<a href="https://www.google.com">Click here to visit Google</a>
Browser Display:
Click here to visit Google (rendered as a clickable link)
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
href | Specifies the destination URL or resource | href="https://example.com" |
target | Defines where to open the link | target="_blank" |
title | Provides additional information (tooltip) | title="Opens Google in a new tab" |
Understanding URLs in href
Absolute URL:
Links to an external website using the full web address.
<a href="https://www.google.com">Visit Google</a>
Relative URL:
Links to a page within the same website.
<a href="7.html">Lesson 7</a>
<a href="pages/about.html">About Us</a>
<a href="../index.html">Home</a>
Email Link:
Opens the user’s default email client.
<a href="mailto:me@example.com">Send email to me</a>
<a title="Send email to me" href="mailto:me@example.com">Send email</a>
Telephone Link:
Opens the user’s default phone app (mainly for mobile).
<a href="tel:+1234567890">Call us</a>
The target Attribute
The target attribute specifies where the linked document will open.
| Value | Description |
|---|---|
_self | Opens in the same tab/window (default) |
_blank | Opens in a new tab/window |
_parent | Opens in the parent frame |
_top | Opens in the full body of the window |
Examples:
<!-- Opens in the same tab (default) -->
<a href="7.html">Lesson 7</a>
<!-- Opens in a new tab -->
<a href="7.html" target="_blank">Lesson in a new tab/window</a>
<!-- Opens Google in a new tab -->
<a href="https://www.google.com" target="_blank">Search Google</a>
Links with Images
You can wrap an image inside an anchor to make the image clickable.
<a href="https://example.com">
<img src="logo.png" alt="Company Logo">
</a>
Link States (CSS)
Links have different states that can be styled:
| State | Description |
|---|---|
:link | Unvisited link |
:visited | Visited link |
:hover | Mouse hover over link |
:active | Clicking on link |
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comments and Anchor Elements</title>
</head>
<body>
<h1>Comments and Hyperlinks</h1>
<!-- ====== SECTION 1: BASIC LINKS ====== -->
<h2>1. Basic Links</h2>
<!-- External link -->
<p><a href="https://www.google.com">Visit Google</a></p>
<!-- Relative link within the same site -->
<p><a href="7.html">Go to Lesson 7</a></p>
<!-- Link with title attribute for tooltip -->
<p>
<a href="https://www.wikipedia.org" title="Wikipedia - The Free Encyclopedia">
Visit Wikipedia
</a>
</p>
<hr>
<!-- ====== SECTION 2: TARGET ATTRIBUTE ====== -->
<h2>2. Target Attribute</h2>
<!-- Opens in the same tab -->
<p><a href="https://www.example.com" target="_self">Open in same tab</a></p>
<!-- Opens in a new tab -->
<p><a href="https://www.example.com" target="_blank">Open in new tab</a></p>
<hr>
<!-- ====== SECTION 3: EMAIL AND PHONE LINKS ====== -->
<h2>3. Email and Phone Links</h2>
<!-- Email link -->
<p><a href="mailto:info@example.com">Send us an email</a></p>
<!-- Email with subject -->
<p>
<a href="mailto:info@example.com?subject=Inquiry%20About%20Services">
Email with subject
</a>
</p>
<!-- Phone link -->
<p><a href="tel:+1234567890">Call us: (123) 456-7890</a></p>
<hr>
<!-- ====== SECTION 4: IMAGES AS LINKS ====== -->
<h2>4. Image as a Link</h2>
<a href="https://www.example.com" target="_blank">
<img src="https://via.placeholder.com/200x100/007bff/ffffff?text=Click+Me"
alt="Click to visit example.com">
</a>
<hr>
<!-- ====== SECTION 5: NAVIGATION MENU ====== -->
<h2>5. Navigation Menu</h2>
<nav>
<!-- TODO: Add styling to make this look like a real menu -->
<a href="index.html">Home</a> |
<a href="about.html">About</a> |
<a href="services.html">Services</a> |
<a href="contact.html">Contact</a>
</nav>
<hr>
<!-- ====== SECTION 6: COMMENTS IN ACTION ====== -->
<h2>6. Debugging with Comments</h2>
<!-- This link is temporarily disabled -->
<!-- <p><a href="new-page.html">New Page (coming soon)</a></p> -->
<p><a href="current-page.html">Current Page</a></p>
<!--
======================================================
NOTES:
- The link above was disabled because the page isn't ready
- Will be enabled in the next release
- Created by: Development Team
- Date: January 2024
======================================================
-->
</body>
</html>
Quick Reference
| Element/Attribute | Purpose | Example |
|---|---|---|
<!-- --> | Comment | <!-- This is a comment --> |
<a> | Anchor element | <a href="url">Link text</a> |
href | Destination URL | href="https://google.com" |
target="_blank" | Open in new tab | target="_blank" |
mailto: | Email link | href="mailto:me@example.com" |
tel: | Phone link | href="tel:+1234567890" |
title | Tooltip | title="More info" |
Best Practices
โ Do This:
<!-- Use descriptive link text -->
<a href="about.html">Learn about our company</a>
<!-- Add title for clarity -->
<a href="https://example.com" title="External website">Example</a>
<!-- Use target="_blank" for external links -->
<a href="https://google.com" target="_blank">Search Google</a>
<!-- Add security for external links -->
<a href="https://external.com" target="_blank" rel="noopener noreferrer">
External Site
</a>
โ Don’t Do This:
<!-- Don't use vague link text -->
<a href="about.html">Click here</a>
<!-- Don't use target="_blank" without security -->
<a href="https://external.com" target="_blank">External</a>
<!-- Always add rel="noopener noreferrer" for security -->
<!-- Don't use title for content that should be visible -->
<a href="page.html" title="Click to learn more">Learn More</a>
Pro Tip: Always use rel="noopener noreferrer" when using target="_blank" with external links. This prevents the new page from accessing the window.opener object, which can be a security risk.
9. img, map, and area Elements
Images make web pages visually appealing and engaging. The <img>, <map>, and <area> elements work together to display images and create interactive clickable regions within them.
The Image Element <img>
The <img> element is used to embed images into a webpage.
Basic Syntax:
<img src="path/to/image" alt="description of the image" width="600" height="400">
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
src | Specifies the image source URL | src="images/photo.jpg" |
alt | Provides alternative text (accessibility) | alt="A beautiful sunset" |
width | Specifies image width in pixels | width="600" |
height | Specifies image height in pixels | height="400" |
Key Points:
- The
srcattribute can take absolute or relative URLs - The
altattribute is essential for accessibility (screen readers use it) alttext appears if the image fails to loadwidthandheighthelp prevent layout shifting while the image loads- The
<img>element is self-closing (no closing tag needed)
Examples:
<!-- Image from external URL -->
<img src="https://example.com/logo.png" alt="Company Logo">
<!-- Image from local folder -->
<img src="images/profile.jpg" alt="Profile photo of John">
<!-- Image with specific dimensions -->
<img src="banner.jpg" alt="Website banner" width="800" height="300">
<!-- Image with proper alt text for accessibility -->
<img src="chart.png" alt="Bar chart showing sales growth from 2020 to 2024">
The Map and Area Elements <map> & <area>
These elements work together to create image maps โ images with clickable regions that link to different URLs.
Basic Syntax:
<img src="path/to/image" usemap="#image-map">
<map name="image-map">
<area shape="rect" coords="316,11,603,198" alt="Lesson 5" href="5.html">
<area shape="rect" coords="100,280,230,555" alt="Lesson 6" href="6.html">
<area shape="rect" coords="244,215,608,566" alt="Lesson 7" href="7.html">
</map>
How It Works:
- The
<img>uses theusemapattribute to reference the map - The
<map>uses thenameattribute to identify itself - Each
<area>defines a clickable region on the image
The Area Element <area>
The <area> element defines a clickable region within an image map.
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
shape | Defines the shape of the clickable area | shape="rect" |
coords | Specifies the coordinates of the shape | coords="x1,y1,x2,y2" |
href | URL to navigate to when clicked | href="page.html" |
alt | Alternative text for accessibility | alt="Link to page" |
target | Where to open the link | target="_blank" |
Shape Types and Coordinates:
| Shape | Description | Coordinates Format | Example |
|---|---|---|---|
rect | Rectangle | coords="x1,y1,x2,y2" (top-left, bottom-right) | coords="0,0,100,50" |
circle | Circle | coords="x,y,r" (center x, center y, radius) | coords="50,50,30" |
polygon | Polygon | coords="x1,y1,x2,y2,x3,y3,..." (multiple points) | coords="0,0,100,0,50,100" |
default | Entire image | No coordinates needed | shape="default" |
Image Map Examples
1. Rectangular Areas:
<img src="menu.png" usemap="#menu-map" alt="Navigation menu">
<map name="menu-map">
<!-- Rectangle area -->
<area shape="rect" coords="10,10,100,50" alt="Home" href="index.html">
<area shape="rect" coords="120,10,210,50" alt="About" href="about.html">
<area shape="rect" coords="230,10,350,50" alt="Contact" href="contact.html">
</map>
2. Circular Areas:
<img src="planets.png" usemap="#planet-map" alt="Solar system">
<map name="planet-map">
<!-- Circle area: center at (100,100) with radius 30 -->
<area shape="circle" coords="100,100,30" alt="Sun" href="sun.html">
<area shape="circle" coords="250,80,15" alt="Mercury" href="mercury.html">
<area shape="circle" coords="350,100,25" alt="Venus" href="venus.html">
</map>
3. Polygon Areas:
<img src="map.png" usemap="#country-map" alt="World map">
<map name="country-map">
<!-- Polygon area for irregular shapes -->
<area shape="polygon" coords="100,50,200,80,180,150,90,130"
alt="Country A" href="country-a.html">
<area shape="polygon" coords="300,70,400,60,420,140,320,160"
alt="Country B" href="country-b.html">
</map>
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Images and Image Maps</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
h1 { color: #333; }
.image-container {
margin: 20px 0;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
}
img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>Images and Image Maps</h1>
<!-- ====== SECTION 1: BASIC IMAGES ====== -->
<h2>1. Basic Image</h2>
<div class="image-container">
<img src="https://via.placeholder.com/600x200/007bff/ffffff?text=Welcome+to+My+Website"
alt="Welcome banner"
width="600"
height="200">
</div>
<h3>Image with Caption:</h3>
<figure>
<img src="https://via.placeholder.com/400x200/28a745/ffffff?text=Beautiful+Sunset"
alt="A beautiful sunset over the ocean"
width="400"
height="200">
<figcaption>Figure 1: Beautiful sunset over the ocean</figcaption>
</figure>
<hr>
<!-- ====== SECTION 2: IMAGE MAPS ====== -->
<h2>2. Image Maps - Clickable Regions</h2>
<h3>Example 1: Navigation Menu with Rectangles</h3>
<div class="image-container">
<img src="https://via.placeholder.com/600x100/343a40/ffffff?text=Home++|++About++|++Services++|++Contact"
alt="Navigation menu"
usemap="#nav-map"
width="600"
height="100">
<map name="nav-map">
<!-- Each navigation item is a rectangular area -->
<area shape="rect" coords="0,0,150,100" alt="Home" href="#home" title="Go to Home">
<area shape="rect" coords="150,0,300,100" alt="About" href="#about" title="Learn About Us">
<area shape="rect" coords="300,0,450,100" alt="Services" href="#services" title="Our Services">
<area shape="rect" coords="450,0,600,100" alt="Contact" href="#contact" title="Contact Us">
</map>
</div>
<h3>Example 2: Interactive Map with Circles</h3>
<div class="image-container">
<img src="https://via.placeholder.com/500x300/6c757d/ffffff?text=Click+on+a+circle"
alt="Interactive map with clickable circles"
usemap="#circle-map"
width="500"
height="300">
<map name="circle-map">
<!-- Three clickable circles -->
<area shape="circle" coords="100,150,50" alt="Circle 1" href="#circle1" title="Click Circle 1">
<area shape="circle" coords="250,150,50" alt="Circle 2" href="#circle2" title="Click Circle 2">
<area shape="circle" coords="400,150,50" alt="Circle 3" href="#circle3" title="Click Circle 3">
</map>
</div>
<h3>Example 3: Complex Image Map</h3>
<div class="image-container">
<img src="https://via.placeholder.com/600x400/ffc107/343a40?text=Clickable+Areas"
alt="Image with multiple clickable areas"
usemap="#complex-map"
width="600"
height="400">
<map name="complex-map">
<!-- Rectangle -->
<area shape="rect" coords="20,20,180,180" alt="Rectangle Area" href="#rect" title="Rectangle Clicked">
<!-- Circle -->
<area shape="circle" coords="380,100,80" alt="Circle Area" href="#circle" title="Circle Clicked">
<!-- Polygon (triangle) -->
<area shape="polygon" coords="50,350,200,250,200,350" alt="Polygon Area" href="#polygon" title="Polygon Clicked">
<!-- Default (entire image) -->
<area shape="default" alt="Default Area" href="#default" title="Click anywhere else">
</map>
</div>
<hr>
<!-- ====== SECTION 3: RESPONSIVE IMAGES ====== -->
<h2>3. Responsive Images</h2>
<div class="image-container">
<img src="https://via.placeholder.com/800x300/17a2b8/ffffff?text=Responsive+Image"
alt="Responsive image example"
style="max-width: 100%; height: auto;">
</div>
<hr>
<!-- ====== SECTION 4: IMAGE WITH CAPTION ====== -->
<h2>4. Image with Figure and Figcaption</h2>
<figure>
<img src="https://via.placeholder.com/500x250/dc3545/ffffff?text=Figure+Example"
alt="Example image with caption"
width="500"
height="250">
<figcaption>
<strong>Figure 2:</strong> This is an example of an image with a caption using
the <code><figure></code> and <code><figcaption></code> elements.
</figcaption>
</figure>
</body>
</html>
Quick Reference
| Element/Attribute | Purpose | Example |
|---|---|---|
<img> | Embed image | <img src="photo.jpg" alt="Description"> |
src | Image source URL | src="images/logo.png" |
alt | Alternative text | alt="Company logo" |
width / height | Image dimensions | width="600" height="400" |
usemap | Reference to image map | usemap="#map-name" |
<map> | Defines clickable regions | <map name="map-name"> |
<area> | Individual clickable region | <area shape="rect" coords="..."> |
shape="rect" | Rectangle area | shape="rect" |
shape="circle" | Circle area | shape="circle" |
shape="polygon" | Polygon area | shape="polygon" |
shape="default" | Entire image area | shape="default" |
Best Practices
โ Do This:
<!-- Always include alt text -->
<img src="chart.png" alt="Sales data chart for 2024">
<!-- Use descriptive filenames -->
<img src="profile-photo-john-doe.jpg" alt="Profile photo of John Doe">
<!-- Specify width and height to prevent layout shift -->
<img src="banner.jpg" alt="Website banner" width="1200" height="400">
<!-- Make images responsive -->
<img src="photo.jpg" alt="Description" style="max-width: 100%; height: auto;">
โ Don’t Do This:
<!-- Don't skip alt text -->
<img src="photo.jpg">
<!-- Don't use generic alt text -->
<img src="chart.png" alt="Chart">
<!-- Don't use images as backgrounds unnecessarily -->
<!-- Use CSS background images instead -->
<!-- Don't use large images without optimizing -->
<!-- Compress and resize images before adding to your site -->
Accessibility Tips
- Always use descriptive
alttext for meaningful images - Use empty
alttext (alt="") for decorative images - Provide detailed
alttext for complex images (charts, infographics) - Consider using
aria-labelfor image maps to provide additional context
<!-- Decorative image -->
<img src="divider.png" alt="">
<!-- Complex image with detailed alt text -->
<img src="infographic.png" alt="Infographic showing website traffic growth from 2020 to 2024, with peaks during holiday seasons">
<!-- Accessible image map -->
<map name="accessible-map">
<area shape="rect" coords="0,0,100,50" alt="Go to Home Page" href="index.html">
<area shape="rect" coords="120,0,200,50" alt="Go to Contact Page" href="contact.html">
</map>
Pro Tip: Always optimize your images before using them on a website. Large image files slow down page loading times. Use tools like ImageOptim, TinyPNG, or modern formats like WebP to reduce file sizes while maintaining quality. Also, consider using the loading="lazy" attribute to lazy-load images off-screen.
10. picture, source Element and favicon
Modern web development requires handling different screen sizes, resolutions, and device capabilities. The <picture> and <source> elements provide a responsive solution, while favicons help with brand recognition in browsers.
The Picture Element <picture> and Source Element <source>
The <picture> element allows you to provide multiple versions of an image, and the browser automatically selects the most appropriate one based on device screen size, resolution, or format support.
Basic Syntax:
<picture>
<source srcset="cat-small.jpg" media="(max-width: 768px)">
<source srcset="cat-medium.jpg" media="(min-width: 769px) and (max-width: 1024px)">
<source srcset="cat-large.jpg" media="(min-width: 1025px)">
<img src="cat-default.jpg" alt="A picture of a cat">
</picture>
How It Works:
- The browser evaluates each
<source>element in order - It selects the first
<source>that matches themediacondition - If none match, it falls back to the
<img>element - The
<img>element is required as a fallback
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
srcset | Specifies the image URL | srcset="image-small.jpg" |
media | Defines media query conditions | media="(max-width: 768px)" |
type | Specifies image MIME type | type="image/webp" |
Responsive Images Examples
1. Screen Size-Based Selection:
<picture>
<!-- Mobile: small image -->
<source srcset="banner-mobile.jpg" media="(max-width: 480px)">
<!-- Tablet: medium image -->
<source srcset="banner-tablet.jpg" media="(max-width: 1024px)">
<!-- Desktop: large image -->
<source srcset="banner-desktop.jpg" media="(min-width: 1025px)">
<!-- Fallback for older browsers -->
<img src="banner-default.jpg" alt="Website banner">
</picture>
2. Format Selection with Fallback:
<picture>
<!-- Modern browsers: WebP format (smaller file size) -->
<source srcset="photo.webp" type="image/webp">
<!-- Other browsers: JPEG format -->
<source srcset="photo.jpg" type="image/jpeg">
<!-- Fallback -->
<img src="photo.jpg" alt="A beautiful landscape">
</picture>
3. Combining Size and Format Selection:
<picture>
<!-- Mobile WebP -->
<source srcset="photo-mobile.webp" media="(max-width: 480px)" type="image/webp">
<!-- Desktop WebP -->
<source srcset="photo-desktop.webp" media="(min-width: 481px)" type="image/webp">
<!-- Mobile JPEG fallback -->
<source srcset="photo-mobile.jpg" media="(max-width: 480px)" type="image/jpeg">
<!-- Desktop JPEG fallback -->
<source srcset="photo-desktop.jpg" media="(min-width: 481px)" type="image/jpeg">
<!-- Final fallback -->
<img src="photo-default.jpg" alt="A beautiful landscape">
</picture>
4. Art Direction:
<picture>
<!-- Mobile: crop to show main subject -->
<source srcset="portrait-mobile.jpg" media="(max-width: 768px)">
<!-- Desktop: show full image -->
<source srcset="portrait-desktop.jpg" media="(min-width: 769px)">
<img src="portrait-default.jpg" alt="Team portrait">
</picture>
5. High-DPI Displays:
<picture>
<!-- Retina display: 2x resolution -->
<source srcset="logo-2x.png" media="(-webkit-min-device-pixel-ratio: 2)">
<!-- Standard display: 1x resolution -->
<source srcset="logo-1x.png" media="(-webkit-min-device-pixel-ratio: 1)">
<img src="logo-1x.png" alt="Company logo">
</picture>
The Favicon
A favicon (favorites icon) is a small icon that represents a website. It appears in browser tabs, bookmarks, and address bars.
Basic Syntax:
<link rel="icon" href="favicon.ico" type="image/x-icon">
Complete Favicon Setup:
<head>
<!-- Standard favicon for older browsers -->
<link rel="icon" href="favicon.ico" type="image/x-icon">
<!-- PNG format for modern browsers -->
<link rel="icon" href="favicon-32x32.png" type="image/png" sizes="32x32">
<link rel="icon" href="favicon-16x16.png" type="image/png" sizes="16x16">
<!-- Apple touch icon for iOS devices -->
<link rel="apple-touch-icon" href="apple-touch-icon.png" sizes="180x180">
<!-- Android Chrome icons -->
<link rel="manifest" href="site.webmanifest">
<!-- Microsoft Windows tiles -->
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
</head>
Favicon Formats:
| Format | Support | Best For |
|---|---|---|
.ico | All browsers | Legacy and universal support |
.png | Modern browsers | High-quality icons |
.svg | Modern browsers | Scalable vector icons |
.gif | Most browsers | Animated icons |
.jpg | Most browsers | Photographic icons |
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Images and Favicon</title>
<!-- ====== FAVICON ====== -->
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" href="favicon-32x32.png" type="image/png" sizes="32x32">
<link rel="icon" href="favicon-16x16.png" type="image/png" sizes="16x16">
<link rel="apple-touch-icon" href="apple-touch-icon.png" sizes="180x180">
<style>
body {
font-family: Arial, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
h1 { color: #333; }
.example {
margin: 30px 0;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
background: #f9f9f9;
}
.example img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>Responsive Images & Favicon</h1>
<!-- ====== EXAMPLE 1: BASIC RESPONSIVE IMAGE ====== -->
<div class="example">
<h2>1. Responsive Image (Screen Size)</h2>
<picture>
<!-- Mobile: 0-768px -->
<source srcset="https://via.placeholder.com/400x300/007bff/ffffff?text=Mobile"
media="(max-width: 768px)">
<!-- Tablet: 769-1024px -->
<source srcset="https://via.placeholder.com/800x400/28a745/ffffff?text=Tablet"
media="(min-width: 769px) and (max-width: 1024px)">
<!-- Desktop: 1025px+ -->
<source srcset="https://via.placeholder.com/1200x500/dc3545/ffffff?text=Desktop"
media="(min-width: 1025px)">
<!-- Fallback -->
<img src="https://via.placeholder.com/800x400/6c757d/ffffff?text=Default"
alt="Responsive image example">
</picture>
<p><small>Resize your browser to see different images</small></p>
</div>
<!-- ====== EXAMPLE 2: FORMAT SELECTION ====== -->
<div class="example">
<h2>2. Format Selection (WebP vs JPEG)</h2>
<picture>
<!-- Modern: WebP format -->
<source srcset="https://via.placeholder.com/600x300/17a2b8/ffffff?text=WebP"
type="image/webp">
<!-- Fallback: JPEG -->
<source srcset="https://via.placeholder.com/600x300/17a2b8/ffffff?text=JPEG"
type="image/jpeg">
<img src="https://via.placeholder.com/600x300/6c757d/ffffff?text=Fallback"
alt="Format selection example">
</picture>
<p><small>Your browser selects the best format it supports</small></p>
</div>
<!-- ====== EXAMPLE 3: ART DIRECTION ====== -->
<div class="example">
<h2>3. Art Direction (Different Crops)</h2>
<picture>
<!-- Mobile: Cropped image -->
<source srcset="https://via.placeholder.com/400x400/ffc107/343a40?text=Cropped"
media="(max-width: 768px)">
<!-- Desktop: Full image -->
<source srcset="https://via.placeholder.com/800x300/ffc107/343a40?text=Full"
media="(min-width: 769px)">
<img src="https://via.placeholder.com/600x300/6c757d/ffffff?text=Default"
alt="Art direction example">
</picture>
<p><small>Mobile shows a cropped version; desktop shows the full image</small></p>
</div>
<!-- ====== EXAMPLE 4: MULTIPLE SOURCES ====== -->
<div class="example">
<h2>4. Multiple Sources (Size + Format)</h2>
<picture>
<!-- Mobile WebP -->
<source srcset="https://via.placeholder.com/400x200/6610f2/ffffff?text=Mobile+WebP"
media="(max-width: 768px)"
type="image/webp">
<!-- Desktop WebP -->
<source srcset="https://via.placeholder.com/1000x300/6610f2/ffffff?text=Desktop+WebP"
media="(min-width: 769px)"
type="image/webp">
<!-- Mobile Fallback -->
<source srcset="https://via.placeholder.com/400x200/6610f2/ffffff?text=Mobile+JPEG"
media="(max-width: 768px)"
type="image/jpeg">
<!-- Desktop Fallback -->
<source srcset="https://via.placeholder.com/1000x300/6610f2/ffffff?text=Desktop+JPEG"
media="(min-width: 769px)"
type="image/jpeg">
<!-- Final fallback -->
<img src="https://via.placeholder.com/600x200/6c757d/ffffff?text=Fallback"
alt="Multiple sources example">
</picture>
</div>
<!-- ====== EXAMPLE 5: HIGH-DPI DISPLAYS ====== -->
<div class="example">
<h2>5. High-DPI Display Support</h2>
<picture>
<!-- Retina display (2x) -->
<source srcset="https://via.placeholder.com/800x200/20c997/ffffff?text=Retina+2x"
media="(-webkit-min-device-pixel-ratio: 2)">
<!-- Standard display (1x) -->
<source srcset="https://via.placeholder.com/400x200/20c997/ffffff?text=Standard+1x"
media="(-webkit-min-device-pixel-ratio: 1)">
<img src="https://via.placeholder.com/400x200/6c757d/ffffff?text=Default"
alt="High-DPI display example">
</picture>
</div>
<!-- ====== EXAMPLE 6: FAVICON INFORMATION ====== -->
<div class="example">
<h2>6. Favicon Information</h2>
<p>This page uses a favicon. Look at the browser tab!</p>
<h3>Recommended Favicon Sizes:</h3>
<ul>
<li>favicon.ico โ 16x16 (legacy browsers)</li>
<li>favicon-16x16.png โ 16x16 (modern browsers)</li>
<li>favicon-32x32.png โ 32x32 (modern browsers)</li>
<li>apple-touch-icon.png โ 180x180 (iOS)</li>
<li>android-chrome-192x192.png โ 192x192 (Android)</li>
<li>android-chrome-512x512.png โ 512x512 (Android)</li>
</ul>
<h3>How to Create a Favicon:</h3>
<ol>
<li>Design your icon (square recommended)</li>
<li>Export to multiple sizes</li>
<li>Add the <code><link></code> elements to your HTML</li>
<li>Create a <code>site.webmanifest</code> file for PWA support</li>
</ol>
<h3>Example site.webmanifest:</h3>
<pre>
{
"name": "My Website",
"short_name": "MySite",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
</pre>
</div>
</body>
</html>
Quick Reference
| Element/Attribute | Purpose | Example |
|---|---|---|
<picture> | Container for multiple image sources | <picture>...</picture> |
<source> | Alternative image version | <source srcset="img.webp" type="image/webp"> |
srcset | Image URL for the source | srcset="photo.jpg" |
media | Media query condition | media="(max-width: 768px)" |
type | Image MIME type | type="image/webp" |
<link rel="icon"> | Defines favicon | <link rel="icon" href="favicon.ico"> |
Best Practices
โ Do This:
<!-- Always include the img element as fallback -->
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Description">
</picture>
<!-- Use WebP format for better compression -->
<source srcset="photo.webp" type="image/webp">
<source srcset="photo.jpg" type="image/jpeg">
<!-- Include multiple favicon sizes -->
<link rel="icon" href="favicon.ico" sizes="any">
<link rel="icon" href="favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="favicon-16x16.png" sizes="16x16" type="image/png">
<!-- Use meaningful media queries -->
<source srcset="mobile.jpg" media="(max-width: 767px)">
<source srcset="tablet.jpg" media="(min-width: 768px) and (max-width: 1023px)">
<source srcset="desktop.jpg" media="(min-width: 1024px)">
โ Don’t Do This:
<!-- Don't forget the img element -->
<picture>
<source srcset="photo.webp" type="image/webp">
<!-- Missing fallback img -->
</picture>
<!-- Don't use overly complex media queries -->
<source srcset="image.jpg" media="(min-width: 768px) and (max-width: 850px) and (orientation: portrait)">
<!-- Don't use only one favicon format -->
<link rel="icon" href="favicon.ico">
<!-- Missing PNG versions for modern browsers -->
<!-- Don't use large, unoptimized favicons -->
<link rel="icon" href="favicon-2000x2000.png" sizes="2000x2000">
Performance Tips
- Choose the right format:
- WebP: Best for modern browsers (smaller file size)
- JPEG: Best for photographs
- PNG: Best for images with transparency
- SVG: Best for logos and icons
- Use appropriate sizes:
- Mobile: Smaller images save bandwidth
- Desktop: Larger images for better quality
- Retina: 2x images for high-DPI displays
- Lazy loading:
<img src="image.jpg" alt="Description" loading="lazy">
- Set width and height:
<img src="image.jpg" alt="Description" width="800" height="600">
Pro Tip: Use online tools like RealFaviconGenerator to generate all favicon sizes and formats at once. For responsive images, consider using a CDN or image service that automatically resizes and formats images based on the request.
11. Tables
Tables in HTML are used to display structured, tabular data in rows and columns. They are ideal for presenting information like product lists, schedules, pricing tables, and more.
Basic Table Structure
A table consists of rows (<tr>), which contain cells (<td> or <th>). The <th> elements define headers, and <td> elements contain data.
Basic Syntax:
<table>
<caption>Product list</caption>
<tr>
<th colspan="2">Product Name</th>
<th>Price</th>
</tr>
<tr>
<td>Product A</td>
<td>Product A</td>
<td>$10.99</td>
</tr>
<tr>
<td>Product B</td>
<td>Product B</td>
<td>$25.49</td>
</tr>
</table>
Table Elements
| Element | Purpose | Example |
|---|---|---|
<table> | Defines a table | <table>...</table> |
<caption> | Adds a title to the table | <caption>Product List</caption> |
<tr> | Defines a table row | <tr>...</tr> |
<th> | Defines a header cell | <th>Name</th> |
<td> | Defines a data cell | <td>John</td> |
<colspan> | Merges columns horizontally | colspan="2" |
<rowspan> | Merges rows vertically | rowspan="3" |
Table Headers <th>
Header cells can be horizontal (top row) or vertical (first column).
Horizontal Headers (Default):
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>Alice</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Bob</td>
<td>30</td>
<td>London</td>
</tr>
</table>
Vertical Headers:
<table>
<tr>
<th>Name</th>
<td>Alice</td>
<td>Bob</td>
</tr>
<tr>
<th>Age</th>
<td>25</td>
<td>30</td>
</tr>
<tr>
<th>City</th>
<td>New York</td>
<td>London</td>
</tr>
</table>
Merging Cells
Colspan (Merge Columns):
<table>
<tr>
<th colspan="3">Employee Information</th>
</tr>
<tr>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
<tr>
<td>John</td>
<td>IT</td>
<td>$60,000</td>
</tr>
</table>
Rowspan (Merge Rows):
<table>
<tr>
<th>Name</th>
<td>John</td>
</tr>
<tr>
<th rowspan="2">Contact</th>
<td>john@example.com</td>
</tr>
<tr>
<td>+1 234-567-890</td>
</tr>
</table>
Combined Colspan and Rowspan:
<table>
<tr>
<th rowspan="2">Name</th>
<th colspan="2">Contact Details</th>
</tr>
<tr>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>Alice</td>
<td>alice@email.com</td>
<td>555-1234</td>
</tr>
</table>
Complete Table Examples
Example 1: Product Catalog
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tables Example</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #007bff;
color: white;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f1f1f1;
}
caption {
font-size: 1.5em;
margin-bottom: 10px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>HTML Tables</h1>
<!-- ====== EXAMPLE 1: BASIC PRODUCT TABLE ====== -->
<h2>1. Product Catalog</h2>
<table>
<caption>Product Catalog 2024</caption>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Category</th>
<th>Price</th>
<th>Stock</th>
</tr>
<tr>
<td>P001</td>
<td>Wireless Mouse</td>
<td>Electronics</td>
<td>$29.99</td>
<td>45</td>
</tr>
<tr>
<td>P002</td>
<td>USB-C Cable</td>
<td>Accessories</td>
<td>$12.99</td>
<td>120</td>
</tr>
<tr>
<td>P003</td>
<td>Bluetooth Speaker</td>
<td>Electronics</td>
<td>$49.99</td>
<td>18</td>
</tr>
<tr>
<td>P004</td>
<td>Notebook Set</td>
<td>Stationery</td>
<td>$8.50</td>
<td>200</td>
</tr>
</table>
<br>
<!-- ====== EXAMPLE 2: EMPLOYEE DATA ====== -->
<h2>2. Employee Directory</h2>
<table>
<caption>Employee Directory</caption>
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Department</th>
<th>Position</th>
<th>Salary</th>
</tr>
<tr>
<td>E101</td>
<td>Sarah Johnson</td>
<td>Marketing</td>
<td>Manager</td>
<td>$75,000</td>
</tr>
<tr>
<td>E102</td>
<td>Mike Davis</td>
<td>IT</td>
<td>Developer</td>
<td>$68,000</td>
</tr>
<tr>
<td>E103</td>
<td>Emily Clark</td>
<td>HR</td>
<td>Recruiter</td>
<td>$55,000</td>
</tr>
</table>
<br>
<!-- ====== EXAMPLE 3: MERGING CELLS ====== -->
<h2>3. Merging Cells (Colspan & Rowspan)</h2>
<table>
<caption>Student Course Schedule</caption>
<tr>
<th colspan="4">Spring 2025 Semester</th>
</tr>
<tr>
<th>Student Name</th>
<th>Course</th>
<th>Instructor</th>
<th>Credits</th>
</tr>
<tr>
<td rowspan="3">Alice Smith</td>
<td>Mathematics 101</td>
<td>Dr. Brown</td>
<td>3</td>
</tr>
<tr>
<td>Physics 201</td>
<td>Prof. Wilson</td>
<td>4</td>
</tr>
<tr>
<td>Computer Science 101</td>
<td>Dr. Lee</td>
<td>3</td>
</tr>
<tr>
<td rowspan="2">Bob Johnson</td>
<td>English 101</td>
<td>Prof. Taylor</td>
<td>3</td>
</tr>
<tr>
<td>History 201</td>
<td>Dr. Adams</td>
<td>3</td>
</tr>
</table>
<br>
<!-- ====== EXAMPLE 4: VERTICAL HEADERS ====== -->
<h2>4. Vertical Headers</h2>
<table>
<caption>Weekly Weather Forecast</caption>
<tr>
<th>Day</th>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
<tr>
<th>Temperature (ยฐF)</th>
<td>72ยฐ</td>
<td>68ยฐ</td>
<td>75ยฐ</td>
<td>70ยฐ</td>
<td>73ยฐ</td>
</tr>
<tr>
<th>Conditions</th>
<td>โ๏ธ Sunny</td>
<td>โ
Cloudy</td>
<td>โ๏ธ Sunny</td>
<td>๐ง๏ธ Rainy</td>
<td>โ๏ธ Sunny</td>
</tr>
<tr>
<th>Humidity</th>
<td>45%</td>
<td>60%</td>
<td>40%</td>
<td>80%</td>
<td>50%</td>
</tr>
</table>
<br>
<!-- ====== EXAMPLE 5: COMPLEX TABLE ====== -->
<h2>5. Complex Table (Monthly Sales Report)</h2>
<table>
<caption>Monthly Sales Report - Q1 2024</caption>
<tr>
<th rowspan="2">Product</th>
<th colspan="3">January</th>
<th colspan="3">February</th>
<th colspan="3">March</th>
<th rowspan="2">Total</th>
</tr>
<tr>
<th>Units</th>
<th>Revenue</th>
<th>Profit</th>
<th>Units</th>
<th>Revenue</th>
<th>Profit</th>
<th>Units</th>
<th>Revenue</th>
<th>Profit</th>
</tr>
<tr>
<td>Product A</td>
<td>150</td>
<td>$4,500</td>
<td>$900</td>
<td>180</td>
<td>$5,400</td>
<td>$1,080</td>
<td>200</td>
<td>$6,000</td>
<td>$1,200</td>
<td>$15,900</td>
</tr>
<tr>
<td>Product B</td>
<td>80</td>
<td>$3,200</td>
<td>$640</td>
<td>90</td>
<td>$3,600</td>
<td>$720</td>
<td>100</td>
<td>$4,000</td>
<td>$800</td>
<td>$10,800</td>
</tr>
<tr>
<td>Product C</td>
<td>50</td>
<td>$1,500</td>
<td>$300</td>
<td>60</td>
<td>$1,800</td>
<td>$360</td>
<td>75</td>
<td>$2,250</td>
<td>$450</td>
<td>$5,550</td>
</tr>
<tr>
<th>Total</th>
<th>280</th>
<th>$9,200</th>
<th>$1,840</th>
<th>330</th>
<th>$10,800</th>
<th>$2,160</th>
<th>375</th>
<th>$12,250</th>
<th>$2,450</th>
<th>$32,250</th>
</tr>
</table>
<br>
<!-- ====== EXAMPLE 6: CALENDAR ====== -->
<h2>6. Calendar</h2>
<table>
<caption>March 2025</caption>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td>15</td>
</tr>
<tr>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
<td>22</td>
</tr>
<tr>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
<td>29</td>
</tr>
<tr>
<td>30</td>
<td>31</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
Quick Reference
| Element | Purpose | Example |
|---|---|---|
<table> | Table container | <table> |
<caption> | Table title | <caption>Prices</caption> |
<tr> | Table row | <tr> |
<th> | Header cell (bold, centered) | <th>Name</th> |
<td> | Data cell | <td>John</td> |
colspan | Merge columns | colspan="2" |
rowspan | Merge rows | rowspan="3" |
Best Practices
โ Do This:
<!-- Use <th> for headers -->
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<!-- Use <caption> for accessibility -->
<caption>Employee List</caption>
<!-- Use proper structure -->
<table>
<caption>Data</caption>
<tr>...</tr>
</table>
โ Don’t Do This:
<!-- Don't use <td> for headers -->
<tr>
<td><strong>Name</strong></td>
<td><strong>Age</strong></td>
</tr>
<!-- Don't use tables for layout -->
<table>
<tr>
<td>Header</td>
</tr>
</table>
Pro Tip: Use the <thead>, <tbody>, and <tfoot> elements to structure complex tables for better readability and accessibility. These elements group header, body, and footer rows.
13. Inline and Block-Level Elements
Understanding the difference between block-level and inline elements is crucial for proper HTML structure and layout. Every HTML element has a default display behavior that determines how it appears in the browser.
Block-Level Elements
Block-level elements are used to structure the layout of a page. They create “blocks” of content.
Characteristics:
- Start on a new line
- Take up the full width available (100% of their container)
- Can contain other block-level and inline elements
- Used for page structure and layout
Common Block-Level Elements:
| Element | Purpose | Example |
|---|---|---|
<h1> – <h6> | Headings | <h1>Main Title</h1> |
<p> | Paragraphs | <p>Text content</p> |
<div> | Generic container | <div>Content</div> |
<ul>, <ol>, <dl> | Lists | <ul><li>Item</li></ul> |
<table> | Tables | <table>...</table> |
<blockquote> | Quotations | <blockquote>Quote</blockquote> |
<address> | Contact info | <address>123 Main St</address> |
<form> | Forms | <form>...</form> |
<header>, <footer>, <main>, <section>, <article>, <nav>, <aside> | Semantic containers | <header>Header</header> |
Example:
<!-- These elements each start on a new line -->
<div>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
</div>
Browser Display:
This is a heading
This is a paragraph of text.
* List item 1
* List item 2
Inline-Level Elements
Inline-level elements are used to format text or content within a block-level element.
Characteristics:
- Do not start on a new line
- Only take up the necessary width to contain their content
- Cannot contain block-level elements (with some exceptions)
- Flow within the text like words in a sentence
Common Inline Elements:
| Element | Purpose | Example |
|---|---|---|
<span> | Generic inline container | <span>highlighted</span> |
<a> | Hyperlinks | <a href="url">Link</a> |
<img> | Images | <img src="photo.jpg" alt=""> |
<b>, <strong> | Bold text | <b>Bold</b> |
<i>, <em> | Italic text | <i>Italic</i> |
<cite> | Citations | <cite>Book Title</cite> |
<abbr> | Abbreviations | <abbr>HTML</abbr> |
<input> | Form inputs | <input type="text"> |
<label> | Form labels | <label>Name:</label> |
<button> | Buttons | <button>Click</button> |
<br> | Line breaks | <br> |
<code> | Code snippets | function() |
Example:
<p>
This is a paragraph with
<span style="color: red;">red highlighted text</span>,
a <a href="#">link</a>, and
<img src="icon.png" alt="icon" style="width: 16px; height: 16px;"> an image.
All of these inline elements flow within the text.
</p>
Browser Display:
This is a paragraph with red highlighted text, a link, and [icon] an image. All of these inline elements flow within the text.
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Block vs Inline Elements</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
h1, h2 { color: #333; }
.example {
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 20px;
background: #f9f9f9;
}
.block-demo {
background: #007bff;
color: white;
padding: 10px;
margin: 5px 0;
}
.inline-demo {
background: #ffc107;
padding: 5px;
margin: 2px;
}
.highlight-box {
border: 2px solid #28a745;
padding: 10px;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>Block vs Inline Elements</h1>
<!-- ====== SECTION 1: BLOCK ELEMENTS ====== -->
<h2>1. Block-Level Elements</h2>
<div class="example">
<p><strong>Block elements start on a new line and take full width:</strong></p>
<div class="block-demo">This is a div (block element)</div>
<div class="block-demo">This div starts on a new line</div>
<div class="block-demo">Each div takes the full width</div>
<hr>
<h3>Common Block Elements:</h3>
<ul>
<li><code><div></code> - Generic container</li>
<li><code><h1></code> to <code><h6></code> - Headings</li>
<li><code><p></code> - Paragraphs</li>
<li><code><ul></code>, <code><ol></code> - Lists</li>
<li><code><table></code> - Tables</li>
<li><code><blockquote></code> - Quotes</li>
</ul>
</div>
<!-- ====== SECTION 2: INLINE ELEMENTS ====== -->
<h2>2. Inline Elements</h2>
<div class="example">
<p><strong>Inline elements flow within text and only take necessary space:</strong></p>
<p>
This is a paragraph with
<span class="inline-demo">inline span</span>,
<b class="inline-demo">bold text</b>,
<i class="inline-demo">italic text</i>,
<a href="#" class="inline-demo">a link</a>, and
<img src="https://via.placeholder.com/16" alt="icon" class="inline-demo"> an image.
They all flow within the text.
</p>
<hr>
<h3>Common Inline Elements:</h3>
<ul>
<li><code><span></code> - Generic inline container</li>
<li><code><a></code> - Anchor links</li>
<li><code><img></code> - Images</li>
<li><code><b></code>, <code><strong></code> - Bold text</li>
<li><code><i></code>, <code><em></code> - Italic text</li>
<li><code><cite></code> - Citations</li>
</ul>
</div>
<!-- ====== SECTION 3: SIDE-BY-SIDE COMPARISON ====== -->
<h2>3. Side-by-Side Comparison</h2>
<div class="example">
<table style="width: 100%; border-collapse: collapse;">
<tr>
<th style="background: #007bff; color: white; padding: 10px; border: 1px solid #ddd;">Block Elements</th>
<th style="background: #28a745; color: white; padding: 10px; border: 1px solid #ddd;">Inline Elements</th>
</tr>
<tr>
<td style="padding: 10px; border: 1px solid #ddd; vertical-align: top;">
<ul>
<li>Start on a new line</li>
<li>Take full width</li>
<li>Can contain block and inline</li>
<li>Used for layout/structure</li>
</ul>
</td>
<td style="padding: 10px; border: 1px solid #ddd; vertical-align: top;">
<ul>
<li>Do not start on a new line</li>
<li>Take only necessary width</li>
<li>Cannot contain block elements</li>
<li>Used for text formatting</li>
</ul>
</td>
</tr>
</table>
</div>
<!-- ====== SECTION 4: VISUAL DEMONSTRATION ====== -->
<h2>4. Visual Demonstration</h2>
<div class="example">
<h3>Block Elements in Action:</h3>
<div style="border: 2px solid #007bff; padding: 10px;">
<h4 style="background: #e9ecef; padding: 10px;">Heading (block)</h4>
<p style="background: #e9ecef; padding: 10px;">Paragraph 1 (block) - This is a block element that starts on a new line and takes the full width.</p>
<p style="background: #e9ecef; padding: 10px;">Paragraph 2 (block) - Notice how each paragraph starts on a new line.</p>
</div>
<br>
<h3>Inline Elements in Action:</h3>
<div style="border: 2px solid #28a745; padding: 10px;">
<p>
This text contains
<span style="background: #ffc107; padding: 2px 5px;">inline span</span>,
<strong style="background: #ffc107; padding: 2px 5px;">strong</strong>,
<em style="background: #ffc107; padding: 2px 5px;">emphasis</em>,
<a href="#" style="background: #ffc107; padding: 2px 5px;">link</a>, and
<img src="https://via.placeholder.com/20" alt="icon" style="background: #ffc107; padding: 2px;">
all within the same line.
</p>
</div>
</div>
<!-- ====== SECTION 5: NESTING RULES ====== -->
<h2>5. Nesting Rules</h2>
<div class="example">
<h3>โ
Correct Nesting:</h3>
<div style="border: 2px solid #28a745; padding: 10px; margin: 10px 0; background: #d4edda;">
<h4>Block containing Inline:</h4>
<p>This is a paragraph with <span style="color: red;">inline text</span> and <a href="#">a link</a>.</p>
</div>
<div style="border: 2px solid #28a745; padding: 10px; margin: 10px 0; background: #d4edda;">
<h4>Block containing Block:</h4>
<div style="background: #f8f9fa; padding: 5px;">
<p>This is a paragraph inside a div.</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
</div>
</div>
<h3>โ Incorrect Nesting:</h3>
<div style="border: 2px solid #dc3545; padding: 10px; margin: 10px 0; background: #f8d7da;">
<h4>Inline containing Block (Invalid):</h4>
<p style="background: #ffc107; padding: 5px;">
<span>
<h5 style="margin: 0;">This heading inside a span is invalid!</h5>
</span>
</p>
<p><small>Inline elements cannot contain block-level elements.</small></p>
</div>
</div>
<!-- ====== SECTION 6: THE DIV AND SPAN ====== -->
<h2>6. The Div and Span Elements</h2>
<div class="example">
<h3>Div (Block) - Used for grouping content:</h3>
<div style="background: #e9ecef; padding: 15px; border-radius: 5px;">
<h4>This is inside a div</h4>
<p>All of this content is grouped together.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
<br>
<h3>Span (Inline) - Used for styling specific parts:</h3>
<p>
This text has a
<span style="color: #007bff; font-weight: bold;">blue bold phrase</span>
and a
<span style="color: #28a745; font-style: italic;">green italic phrase</span>.
</p>
<p>
You can also use
<span style="background: #ffc107; padding: 2px 8px; border-radius: 4px;">spans to create highlighted boxes</span>
within your text.
</p>
</div>
<!-- ====== SECTION 7: CHANGING DISPLAY PROPERTY ====== -->
<h2>7. Changing Display with CSS</h2>
<div class="example">
<h3>Default Block โ Inline:</h3>
<div style="display: inline; background: #007bff; color: white; padding: 5px;">This div is inline</div>
<div style="display: inline; background: #28a745; color: white; padding: 5px;">This div is also inline</div>
<p><small>These divs now behave like inline elements.</small></p>
<h3>Default Inline โ Block:</h3>
<span style="display: block; background: #ffc107; padding: 10px;">This span is block</span>
<span style="display: block; background: #dc3545; color: white; padding: 10px;">This span is also block</span>
<p><small>These spans now behave like block elements.</small></p>
</div>
</body>
</html>
Quick Reference
| Category | Characteristics | Common Elements |
|---|---|---|
| Block | New line, full width, can contain blocks | <div>, <p>, <h1>–<h6>, <ul>, <table> |
| Inline | Same line, only necessary width, cannot contain blocks | <span>, <a>, <img>, <b>, <i>, <em> |
Best Practices
โ Do This:
<!-- Use block elements for structure -->
<div class="container">
<h1>Heading</h1>
<p>Paragraph</p>
</div>
<!-- Use inline elements for text formatting -->
<p>This is <span style="color: red;">important</span> text.</p>
<!-- Nest inline elements inside blocks -->
<p><a href="#">Link</a> within a paragraph.</p>
โ Don’t Do This:
<!-- Don't put block elements inside inline elements -->
<span>
<h1>Invalid!</h1> <!-- This is invalid HTML -->
</span>
<!-- Don't use <div> when <p> is appropriate -->
<div>This is a paragraph but using div</div>
<!-- Don't use <span> for layout -->
<span style="display: block;">This should be a div</span>
Pro Tip: Use block elements for structure and layout, and inline elements for styling and formatting within the content. Remember that you can change an element’s display behavior using CSS (display: block; or display: inline;), but always use semantic HTML first!
14. The Div Element
The <div> (division) element is one of the most commonly used elements in HTML. It is a block-level container that groups and organizes other elements, making it essential for structuring web pages.
What is a Div?
The <div> element is a generic container that has no inherent meaning or styling. It is used purely for grouping and organizing content.
Key Characteristics:
- Block-level element (starts on a new line, takes full width)
- No semantic meaning โ it’s a neutral container
- Used for layout, styling, and structuring content
- Can contain any other HTML elements (both block and inline)
- Often used with
classoridattributes for CSS styling or JavaScript
Basic Syntax:
<div>
<h2>Section Title</h2>
<p>This is content inside a div.</p>
</div>
Why Use Divs?
| Purpose | Example |
|---|---|
| Group related content | Wrapping a section of content together |
| Apply CSS styles | Adding backgrounds, margins, padding to a group |
| Create layouts | Building page structures like headers, footers, sidebars |
| JavaScript targeting | Selecting and manipulating groups of elements |
| Page organization | Making code cleaner and more maintainable |
The class Attribute
The class attribute is used to assign one or more class names to an element. Classes are used by CSS and JavaScript to style or manipulate elements.
<div class="hero">
<h2>Welcome to My Website</h2>
<p>This is a hero section with an image and some text.</p>
</div>
<div class="features">
<h3>Features</h3>
<ul>
<li>Feature 1</li>
<li>Feature 2</li>
<li>Feature 3</li>
</ul>
</div>
Key Points:
- One or more elements can share the same class
- An element can have multiple classes (space-separated)
- Classes are case-sensitive
- Classes are used for styling and scripting
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Div Element</title>
<style>
/* ====== Global Styles ====== */
body {
font-family: Arial, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background: #f4f4f4;
}
h1 {
color: #333;
text-align: center;
padding-bottom: 20px;
border-bottom: 3px solid #007bff;
}
/* ====== Div Styling ====== */
.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
/* Hero Section */
.hero {
background: linear-gradient(135deg, #007bff, #0056b3);
color: white;
padding: 40px 30px;
border-radius: 8px;
text-align: center;
margin-bottom: 20px;
}
.hero h2 {
font-size: 2.5em;
margin-bottom: 10px;
}
.hero p {
font-size: 1.2em;
opacity: 0.9;
}
/* Features Section */
.features {
background: #f8f9fa;
padding: 25px 30px;
border-radius: 8px;
margin-bottom: 20px;
border-left: 4px solid #28a745;
}
.features h3 {
color: #28a745;
margin-top: 0;
}
.features ul {
padding-left: 20px;
}
.features li {
padding: 5px 0;
}
/* Gallery Section */
.gallery {
display: flex;
gap: 15px;
justify-content: center;
flex-wrap: wrap;
padding: 20px;
background: #e9ecef;
border-radius: 8px;
margin-bottom: 20px;
}
.gallery-item {
background: white;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
text-align: center;
flex: 1;
min-width: 120px;
max-width: 200px;
}
.gallery-item .icon {
font-size: 3em;
display: block;
}
/* Footer Section */
.footer {
background: #343a40;
color: white;
text-align: center;
padding: 15px;
border-radius: 8px;
font-size: 0.9em;
}
/* Multiple classes example */
.highlight {
background: #ffc107;
padding: 2px 8px;
border-radius: 4px;
font-weight: bold;
}
.text-muted {
color: #6c757d;
}
.box {
border: 2px solid #007bff;
padding: 15px;
border-radius: 8px;
margin: 10px 0;
}
.box.rounded {
border-radius: 20px;
}
.box.shadow {
box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}
</style>
</head>
<body>
<h1>The Div Element</h1>
<!-- ====== MAIN CONTAINER DIV ====== -->
<div class="container">
<!-- ====== HERO SECTION ====== -->
<div class="hero">
<h2>Welcome to My Website</h2>
<p>This is a hero section that grabs attention with a strong visual presence.</p>
<p style="margin-top: 15px;">
<span style="background: rgba(255,255,255,0.2); padding: 8px 20px; border-radius: 25px;">
Learn More โ
</span>
</p>
</div>
<!-- ====== FEATURES SECTION ====== -->
<div class="features">
<h3>โจ Features</h3>
<ul>
<li><strong>Responsive Design</strong> โ Works on all devices</li>
<li><strong>Fast Performance</strong> โ Optimized for speed</li>
<li><strong>Easy to Customize</strong> โ Flexible and modular</li>
</ul>
</div>
<!-- ====== GALLERY SECTION ====== -->
<div class="gallery">
<div class="gallery-item">
<span class="icon">๐</span>
<h4>Launch</h4>
<p class="text-muted">Start your project</p>
</div>
<div class="gallery-item">
<span class="icon">โก</span>
<h4>Speed</h4>
<p class="text-muted">Lightning fast</p>
</div>
<div class="gallery-item">
<span class="icon">๐จ</span>
<h4>Design</h4>
<p class="text-muted">Beautiful layouts</p>
</div>
<div class="gallery-item">
<span class="icon">๐</span>
<h4>Security</h4>
<p class="text-muted">Safe & reliable</p>
</div>
</div>
<!-- ====== CONTENT SECTIONS WITH CLASSES ====== -->
<h2 style="margin-top: 30px;">Using Classes with Divs</h2>
<!-- Multiple boxes with different class combinations -->
<div class="box">
<h3>Basic Box</h3>
<p>This is a <span class="highlight">standard box</span> with a border.</p>
</div>
<div class="box rounded">
<h3>Rounded Box</h3>
<p>This box has <span class="highlight">rounded corners</span> using the <code>rounded</code> class.</p>
</div>
<div class="box shadow">
<h3>Shadow Box</h3>
<p>This box has a <span class="highlight">drop shadow</span> using the <code>shadow</code> class.</p>
</div>
<div class="box rounded shadow">
<h3>Rounded + Shadow</h3>
<p>This box has <span class="highlight">both rounded corners and a shadow</span> by using multiple classes!</p>
</div>
<!-- ====== NESTED DIVS ====== -->
<h2 style="margin-top: 30px;">Nested Divs</h2>
<div style="background: #e9ecef; padding: 20px; border-radius: 8px;">
<h3>Outer Div</h3>
<p>This is the parent container.</p>
<div style="background: white; padding: 15px; border-radius: 8px; margin-top: 10px;">
<h4>Inner Div 1</h4>
<p>This div is nested inside the outer div.</p>
</div>
<div style="background: white; padding: 15px; border-radius: 8px; margin-top: 10px;">
<h4>Inner Div 2</h4>
<p>You can have multiple nested divs.</p>
<div style="background: #f8f9fa; padding: 10px; border-radius: 4px; margin-top: 10px;">
<p><strong>Deep nesting:</strong> This is a div inside a div inside a div!</p>
</div>
</div>
</div>
<!-- ====== SEMANTIC VS NON-SEMANTIC ====== -->
<h2 style="margin-top: 30px;">Div vs Semantic Elements</h2>
<div style="display: flex; gap: 20px; flex-wrap: wrap;">
<!-- Div-based layout -->
<div style="flex: 1; min-width: 250px; background: #f8f9fa; padding: 15px; border-radius: 8px;">
<h3 style="color: #dc3545;">Using Divs (Non-Semantic)</h3>
<div style="background: white; padding: 10px; border-radius: 4px;">
<div style="font-weight: bold;">Header</div>
<div>Navigation</div>
<div>Content</div>
<div style="color: #6c757d;">Footer</div>
</div>
<p><small>All elements are divs โ lacks meaning.</small></p>
</div>
<!-- Semantic layout -->
<div style="flex: 1; min-width: 250px; background: #d4edda; padding: 15px; border-radius: 8px;">
<h3 style="color: #28a745;">Using Semantic Elements</h3>
<div style="background: white; padding: 10px; border-radius: 4px;">
<header style="font-weight: bold;">Header</header>
<nav>Navigation</nav>
<main>Content</main>
<footer style="color: #6c757d;">Footer</footer>
</div>
<p><small>Semantic elements give meaning to the structure.</small></p>
</div>
</div>
<!-- ====== FOOTER ====== -->
<div class="footer" style="margin-top: 30px;">
© 2025 My Website | Created with HTML & CSS
</div>
</div>
<!-- END OF MAIN CONTAINER -->
</body>
</html>
Div vs Semantic Elements
| Feature | Div | Semantic Elements |
|---|---|---|
| Example | <div> | <header>, <main>, <footer>, <article> |
| Meaning | None (generic container) | Has specific meaning |
| SEO | Neutral | Helps search engines understand structure |
| Accessibility | Neutral | Helps screen readers navigate |
| Best Use | Styling, grouping, layout purposes | Representing logical sections of content |
Best Practices
โ Do This:
<!-- Use divs for styling and grouping -->
<div class="container">
<div class="card">
<h3>Card Title</h3>
<p>Card content</p>
</div>
</div>
<!-- Use descriptive class names -->
<div class="navigation-menu">...</div>
<div class="product-grid">...</div>
<!-- Use multiple classes for modular styling -->
<div class="box rounded shadow highlight">...</div>
โ Don’t Do This:
<!-- Don't use divs when semantic elements are appropriate -->
<!-- Instead of: -->
<div class="header">Header</div>
<!-- Use: -->
<header>Header</header>
<!-- Don't use overly generic class names -->
<div class="div1">...</div>
<div class="container1">...</div>
<!-- Don't over-nest divs unnecessarily -->
<div>
<div>
<div>
<div>Too deep!</div>
</div>
</div>
</div>
Quick Reference
| Element | Type | Purpose |
|---|---|---|
<div> | Block | Generic container for grouping and styling |
class | Attribute | Assigns a CSS class (can be shared) |
id | Attribute | Assigns a unique identifier (must be unique) |
Semantic elements (<header>, <main>, etc.) | Block | Meaningful structure with specific purposes |
Pro Tip: Use <div> when no semantic element fits, but prioritize semantic HTML5 elements (<header>, <nav>, <main>, <section>, <article>, <aside>, <footer>) for better accessibility, SEO, and code readability. Divs are excellent for styling purposes and creating complex layouts!
16. The head Element
The <head> element is a container for metadata and other information about an HTML document. This content is not displayed directly on the webpage but is crucial for the page’s functionality, SEO, styling, and behavior.
What is the head Element?
The <head> element sits between the <!DOCTYPE html> declaration and the <body> element. It contains information that browsers, search engines, and other web services use to understand and process the page.
Key Characteristics:
- Not displayed on the webpage itself
- Contains metadata (data about the data)
- Essential for SEO, styling, scripting, and page settings
- Only one
<head>element per HTML document
Basic Structure:
<!DOCTYPE html>
<html>
<head>
<!-- Metadata and resources go here -->
</head>
<body>
<!-- Visible content goes here -->
</body>
</html>
Common head Elements
| Element | Purpose | Example |
|---|---|---|
<title> | Sets the browser tab title | <title>My Website</title> |
<meta> | Provides metadata (charset, description, viewport) | <meta charset="UTF-8"> |
<base> | Sets base URL for relative links | <base href="https://example.com/"> |
<link> | Links external resources (CSS, favicon) | <link rel="stylesheet" href="style.css"> |
<style> | Internal CSS styles | <style>body { color: red; }</style> |
<script> | JavaScript code or external script | <script src="script.js"></script> |
Detailed Breakdown of Elements
1. Title Element <title>
The <title> element sets the title of the webpage, which appears in the browser tab, search engine results, and bookmarks.
<title>My Page</title>
Browser Display:
- Shows in the browser tab or window title bar
- Used by search engines as the clickable headline in results
- Essential for SEO and user experience
2. Meta Elements <meta>
The <meta> element provides metadata about the HTML document.
Character Encoding:
<meta charset="UTF-8">
- Specifies the character encoding for the document
UTF-8supports all characters and languages- Should be the first meta tag in the head
Page Description:
<meta name="description" content="An example page about HTML basics">
- Provides a brief description of the page
- Used by search engines in search results (SEO)
- Should be concise and accurate
Keywords:
<meta name="keywords" content="HTML, CSS, JavaScript, Web Development">
- Specifies keywords for search engines
- Less important for SEO today but still used by some systems
- Helps search engines understand page content
Viewport (Responsive Design):
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- Makes the webpage look good on all devices
- Sets the initial zoom level and scaling
- Essential for mobile-friendly design
Viewport Options:
| Value | Description |
|---|---|
width=device-width | Sets width to device screen width |
initial-scale=1.0 | Sets initial zoom level to 100% |
maximum-scale=1.0 | Prevents zooming (use with caution) |
user-scalable=yes/no | Allows/disallows user zoom |
3. Base Element <base>
The <base> element defines the base URL for all relative URLs in the document.
<base href="https://mydomain.com/" target="_blank">
Important Notes:
- Only one
<base>element allowed per page - If present, it must be placed before any elements that use URLs
- Use with caution โ it affects all relative links and image paths
Example:
<base href="https://example.com/">
<!-- All relative links will be relative to https://example.com/ -->
<a href="about.html">About</a> <!-- Links to https://example.com/about.html -->
<a href="contact.html">Contact</a> <!-- Links to https://example.com/contact.html -->
4. Link Element <link>
The <link> element links external resources to the document, most commonly CSS stylesheets.
External Stylesheet:
<link rel="stylesheet" href="styles.css">
- Links to an external CSS file
- Allows for separate styling from content
- Improves code organization and reusability
Favicon:
<link rel="icon" href="favicon.ico" type="image/x-icon">
- Defines the website’s favicon
- Appears in browser tabs and bookmarks
Preconnect for Performance:
<link rel="preconnect" href="https://fonts.googleapis.com">
- Pre-establishes connections to external resources
- Improves loading performance
5. Style Element <style>
The <style> element contains internal CSS (Cascading Style Sheets) that styles the document.
<style>
body {
background-color: blue;
color: white;
}
h1 {
font-size: 2em;
text-align: center;
}
</style>
When to Use Internal Styles:
- Small, single-page websites
- Quick prototyping
- Overriding external styles
- Styles that are page-specific
6. Script Element <script>
The <script> element is used to define or import JavaScript code.
Inline JavaScript:
<script>
alert("Welcome!");
console.log("Page loaded");
</script>
External JavaScript File:
<script src="scripts.js"></script>
Async and Defer Loading:
<script src="script.js" async></script> <!-- Loads asynchronously -->
<script src="script.js" defer></script> <!-- Loads after HTML parsing -->
Key Points:
<script>in the<head>loads before the page content- Use
deferor place scripts at the end of<body>for better performance - External scripts improve code organization and caching
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ====== Character Encoding ====== -->
<meta charset="UTF-8">
<!-- ====== Title ====== -->
<title>My Awesome Website</title>
<!-- ====== Meta Tags for SEO ====== -->
<meta name="description" content="Learn HTML basics with this comprehensive guide. Perfect for beginners!">
<meta name="keywords" content="HTML, Web Development, CSS, JavaScript, Programming">
<meta name="author" content="John Doe">
<!-- ====== Viewport for Mobile ====== -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- ====== Base URL ====== -->
<base href="https://mydomain.com/" target="_blank">
<!-- ====== Favicon ====== -->
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon" href="apple-touch-icon.png" sizes="180x180">
<!-- ====== External Stylesheet ====== -->
<link rel="stylesheet" href="styles.css">
<!-- ====== Preconnect for Performance ====== -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- ====== Google Fonts ====== -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
<!-- ====== Internal Styles ====== -->
<style>
/* Global Styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
color: #333;
min-height: 100vh;
padding: 20px;
}
h1 {
color: #007bff;
text-align: center;
margin-bottom: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.highlight {
background: #ffc107;
padding: 2px 8px;
border-radius: 4px;
}
</style>
<!-- ====== External JavaScript ====== -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- ====== Inline JavaScript ====== -->
<script>
// This runs when the page loads
console.log('Page loaded successfully!');
// Alternative: Use DOMContentLoaded for better performance
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM fully loaded and parsed');
});
</script>
</head>
<body>
<div class="container">
<h1>Welcome to My Website</h1>
<p>This page demonstrates the <span class="highlight">head element</span> and all its components.</p>
<p>Look at the browser tab to see the title!</p>
</div>
</body>
</html>
Complete head Element Reference
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ====== REQUIRED ====== -->
<meta charset="UTF-8">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- ====== SEO META TAGS ====== -->
<meta name="description" content="Page description for search engines">
<meta name="keywords" content="keyword1, keyword2, keyword3">
<meta name="author" content="Author Name">
<meta name="robots" content="index, follow">
<!-- ====== SOCIAL MEDIA (Open Graph) ====== -->
<meta property="og:title" content="Page Title">
<meta property="og:description" content="Page description for social media">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:url" content="https://example.com">
<meta name="twitter:card" content="summary_large_image">
<!-- ====== BASE URL ====== -->
<base href="https://example.com/">
<!-- ====== FAVICON ====== -->
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon" href="apple-touch-icon.png" sizes="180x180">
<!-- ====== EXTERNAL STYLES ====== -->
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap">
<!-- ====== INTERNAL STYLES ====== -->
<style>
body { font-family: 'Open Sans', sans-serif; }
</style>
<!-- ====== EXTERNAL SCRIPTS ====== -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- ====== INTERNAL SCRIPTS ====== -->
<script>
console.log('Hello from the head!');
</script>
</head>
<body>
<!-- Visible content -->
</body>
</html>
head Element Reference Table
| Element | Purpose | Required? |
|---|---|---|
<title> | Browser tab title | โ Yes |
<meta charset> | Character encoding | โ Yes |
<meta viewport> | Responsive design | โ Yes |
<meta description> | SEO description | Recommended |
<link> | External resources | Optional |
<style> | Internal CSS | Optional |
<script> | JavaScript | Optional |
<base> | Base URL | Optional |
Best Practices
โ Do This:
<head>
<!-- Always include charset first -->
<meta charset="UTF-8">
<!-- Always include viewport for mobile -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Always include a title -->
<title>Descriptive Page Title</title>
<!-- Write meaningful meta descriptions -->
<meta name="description" content="Concise, accurate page description for search results">
<!-- Use external CSS when possible -->
<link rel="stylesheet" href="styles.css">
<!-- Place scripts at the bottom of body for better performance -->
<!-- Or use async/defer -->
<script src="script.js" defer></script>
</head>
โ Don’t Do This:
<head>
<!-- Don't use generic titles -->
<title>Untitled</title>
<!-- Don't forget viewport -->
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
<!-- Don't write empty or spammy descriptions -->
<meta name="description" content="">
<!-- Don't place script before external styles -->
<script src="script.js"></script>
<link rel="stylesheet" href="styles.css"> <!-- This should come first -->
<!-- Don't use inline styles for large CSS blocks -->
<style>
/* 500+ lines of CSS */ <!-- Use external file instead -->
</style>
</head>
Performance Tips
| Technique | Description | Example |
|---|---|---|
| Preconnect | Pre-establish connections to external domains | <link rel="preconnect" href="https://fonts.googleapis.com"> |
| Prefetch | Pre-load resources likely to be needed | <link rel="prefetch" href="next-page.html"> |
| Defer | Load scripts after HTML parsing | <script src="script.js" defer></script> |
| Async | Load scripts asynchronously | <script src="script.js" async></script> |
| Minify | Reduce file sizes | Use minified CSS and JS files |
Pro Tip: The <head> element is your page’s control center. A well-structured head section improves SEO, page load speed, user experience, and accessibility. Always prioritize the required elements (charset, title, viewport) and add others as needed for your specific use case.
17. Layout Elements (Semantic HTML)
Semantic elements are HTML elements that carry meaning about the content they contain. They describe the purpose of the content rather than just its appearance, making web pages more accessible, SEO-friendly, and maintainable.
Semantic vs. Non-Semantic Elements
| Type | Description | Examples |
|---|---|---|
| Semantic | Elements with meaning that describe content structure | <header>, <nav>, <main>, <article>, <section>, <aside>, <footer>, <details> |
| Non-Semantic | Generic containers with no meaning | <div>, <span> |
Why Use Semantic Elements?
| Benefit | Description |
|---|---|
| Accessibility | Screen readers understand page structure better |
| SEO | Search engines prioritize content based on context |
| Maintainability | Code is easier to read and understand |
| Interoperability | Browsers and tools interpret content correctly |
Common Layout/Semantic Elements
| Element | Purpose | Example |
|---|---|---|
<header> | Introductory content or navigation | Page header, article header |
<nav> | Navigation links | Main menu, breadcrumbs |
<main> | Main content of the page | Primary content area |
<section> | Thematic grouping of content | Chapters, sections |
<article> | Self-contained content | Blog posts, news articles |
<aside> | Side content (tangentially related) | Sidebars, pull quotes |
<footer> | Footer information | Copyright, contact info |
<details> | Expandable content | FAQ sections |
<summary> | Heading for <details> | Clickable summary |
Detailed Explanation
1. Header <header>
The <header> element represents introductory content or a group of navigational aids.
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
Common Uses:
- Page/section titles
- Logos and branding
- Navigation menus
- Search forms
2. Navigation <nav>
The <nav> element defines a section containing navigation links.
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/services">Services</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
Common Uses:
- Primary navigation menus
- Breadcrumb navigation
- Table of contents
- Pagination links
3. Main <main>
The <main> element represents the dominant content of the document. There should be only one per page.
<main>
<h1>Welcome to My Site</h1>
<p>This is the main content of the page.</p>
</main>
Important:
- Only one
<main>per page - Should not be nested inside
<header>,<footer>,<article>, or<aside>
4. Section <section>
The <section> element represents a thematic grouping of content, typically with a heading.
<section>
<h2>Our Services</h2>
<p>We offer a wide range of services to meet your needs.</p>
<ul>
<li>Web Design</li>
<li>Web Development</li>
<li>SEO Optimization</li>
</ul>
</section>
<section>
<h2>Testimonials</h2>
<blockquote>Great service! - John Doe</blockquote>
</section>
When to Use:
- Grouping related content
- Chapters or parts of a document
- Different sections of a homepage
5. Article <article>
The <article> element represents self-contained, independent content that could be distributed or reused.
<article>
<header>
<h2>My Latest Blog Post</h2>
<p>Published on <time datetime="2024-01-15">January 15, 2024</time></p>
</header>
<p>This is my latest blog post, featuring some great tips and tricks for web development.</p>
<footer>
<p>Written by John Doe</p>
</footer>
</article>
When to Use:
- Blog posts
- News articles
- Product cards
- Forum posts
- User comments
6. Aside <aside>
The <aside> element represents content that is tangentially related to the main content.
<aside>
<h3>Related Links</h3>
<ul>
<li><a href="#">Web Development Tutorials</a></li>
<li><a href="#">Design Inspiration</a></li>
<li><a href="#">Best Practices</a></li>
</ul>
</aside>
When to Use:
- Sidebars
- Pull quotes
- Related content
- Advertisements
- Author bio
7. Footer <footer>
The <footer> element represents footer information for its nearest ancestor sectioning content.
<footer>
<p>© 2024 My Website. All rights reserved.</p>
<nav>
<a href="/privacy">Privacy Policy</a> |
<a href="/terms">Terms of Service</a>
</nav>
</footer>
Common Uses:
- Copyright notices
- Contact information
- Site maps
- Legal disclaimers
- Social media links
8. Details & Summary
The <details> and <summary> elements create an expandable/collapsible content section.
<details>
<summary>FAQ</summary>
<p>Here are some frequently asked questions:</p>
<ul>
<li><strong>How do I get started?</strong> - Start by learning HTML basics.</li>
<li><strong>What are the best tools?</strong> - VS Code, Chrome DevTools, and Git.</li>
<li><strong>Is this free?</strong> - Yes, all resources are free.</li>
</ul>
</details>
Key Points:
<summary>provides the visible heading- Clicking the summary toggles the content
- Can be used for FAQs, collapsible menus, and expandable content
- The
openattribute can make it expanded by default
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Semantic Layout Elements</title>
<style>
/* ====== Global Styles ====== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
background: #f4f4f4;
padding: 20px;
}
/* ====== Layout Styles ====== */
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
/* ====== Header ====== */
header {
background: linear-gradient(135deg, #007bff, #0056b3);
color: white;
padding: 30px;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
header h1 {
font-size: 2em;
}
nav ul {
display: flex;
list-style: none;
gap: 20px;
}
nav a {
color: white;
text-decoration: none;
padding: 5px 15px;
border-radius: 5px;
transition: background 0.3s;
}
nav a:hover {
background: rgba(255,255,255,0.2);
}
/* ====== Main Content ====== */
.content-wrapper {
display: flex;
gap: 30px;
padding: 30px;
flex-wrap: wrap;
}
/* ====== Main Area ====== */
main {
flex: 2;
min-width: 300px;
}
main h2 {
color: #007bff;
margin-bottom: 10px;
}
.post-meta {
color: #6c757d;
font-size: 0.9em;
margin-bottom: 15px;
}
/* ====== Article ====== */
article {
background: #f8f9fa;
padding: 25px;
border-radius: 8px;
margin-bottom: 20px;
border-left: 4px solid #007bff;
}
article h3 {
color: #333;
margin-bottom: 5px;
}
/* ====== Section ====== */
section {
margin: 20px 0;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
}
section h2 {
color: #28a745;
}
/* ====== Aside ====== */
aside {
flex: 1;
min-width: 250px;
background: #f8f9fa;
padding: 25px;
border-radius: 8px;
height: fit-content;
border-left: 4px solid #ffc107;
}
aside h3 {
color: #ffc107;
margin-bottom: 10px;
}
aside ul {
list-style: none;
padding: 0;
}
aside li {
padding: 5px 0;
}
aside a {
color: #007bff;
text-decoration: none;
}
aside a:hover {
text-decoration: underline;
}
/* ====== Details/Summary ====== */
details {
margin: 20px 30px 30px;
padding: 15px 20px;
background: #f8f9fa;
border-radius: 8px;
border: 1px solid #ddd;
}
summary {
font-weight: bold;
font-size: 1.1em;
cursor: pointer;
padding: 10px 0;
color: #007bff;
}
summary:hover {
color: #0056b3;
}
details ul {
padding-left: 20px;
margin: 10px 0;
}
details li {
padding: 5px 0;
}
/* ====== Footer ====== */
.footer-main {
background: #343a40;
color: white;
padding: 20px 30px;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.footer-main a {
color: #ffc107;
text-decoration: none;
}
.footer-main a:hover {
text-decoration: underline;
}
.article-footer {
padding: 10px 0;
font-size: 0.9em;
color: #6c757d;
}
/* ====== Responsive ====== */
@media (max-width: 768px) {
header {
flex-direction: column;
text-align: center;
}
nav ul {
flex-direction: column;
gap: 10px;
margin-top: 15px;
}
.content-wrapper {
flex-direction: column;
}
.footer-main {
flex-direction: column;
text-align: center;
gap: 10px;
}
}
</style>
</head>
<body>
<div class="container">
<!-- ====== HEADER ====== -->
<header>
<h1>๐ My Website</h1>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
<!-- ====== CONTENT WRAPPER ====== -->
<div class="content-wrapper">
<!-- ====== MAIN ====== -->
<main>
<h2>Welcome to My Website</h2>
<p>This page demonstrates the use of semantic HTML5 layout elements. Each element has a specific meaning and purpose.</p>
<!-- ====== SECTION ====== -->
<section>
<h2>๐ก Latest Articles</h2>
<!-- ====== ARTICLE 1 ====== -->
<article>
<header style="background: none; padding: 0; color: #333;">
<h3>My Latest Blog Post</h3>
<p class="post-meta">Published on <time datetime="2024-01-15">January 15, 2024</time> by John Doe</p>
</header>
<p>This is my latest blog post, featuring some great tips and tricks for web development. Semantic HTML is essential for modern web development!</p>
<footer class="article-footer">
๐ Category: Web Development | ๐ฌ 12 Comments
</footer>
</article>
<!-- ====== ARTICLE 2 ====== -->
<article>
<header style="background: none; padding: 0; color: #333;">
<h3>Understanding CSS Flexbox</h3>
<p class="post-meta">Published on <time datetime="2024-01-10">January 10, 2024</time> by Jane Smith</p>
</header>
<p>Flexbox is a powerful layout model in CSS. It makes it easy to create responsive designs without using floats or positioning.</p>
<footer class="article-footer">
๐ Category: CSS | ๐ฌ 8 Comments
</footer>
</article>
</section>
</main>
<!-- ====== ASIDE ====== -->
<aside>
<h3>๐ Related Links</h3>
<ul>
<li><a href="#">Web Development Tutorials</a></li>
<li><a href="#">Design Inspiration</a></li>
<li><a href="#">Best Practices for SEO</a></li>
<li><a href="#">Accessibility Guidelines</a></li>
<li><a href="#">HTML5 Cheat Sheet</a></li>
</ul>
<hr style="margin: 20px 0; border-color: #ddd;">
<h3>๐ Quick Stats</h3>
<ul>
<li>๐ 45 Blog Posts</li>
<li>๐ฅ 1,200 Subscribers</li>
<li>โญ 4.8/5 Rating</li>
</ul>
</aside>
</div>
<!-- ====== DETAILS / SUMMARY ====== -->
<details>
<summary>โ Frequently Asked Questions</summary>
<p>Here are some frequently asked questions:</p>
<ul>
<li><strong>How do I get started?</strong> - Start by learning HTML basics, then CSS, then JavaScript.</li>
<li><strong>What are the best tools?</strong> - VS Code for coding, Chrome DevTools for debugging, and Git for version control.</li>
<li><strong>Is this content free?</strong> - Yes, all content on this site is completely free.</li>
<li><strong>How often do you post?</strong> - We post new articles every Tuesday and Thursday.</li>
</ul>
</details>
<!-- ====== FOOTER ====== -->
<footer class="footer-main">
<p>© 2024 My Website. All rights reserved.</p>
<nav>
<a href="#">Privacy Policy</a> |
<a href="#">Terms of Service</a> |
<a href="#">Contact Us</a>
</nav>
</footer>
</div>
</body>
</html>
Semantic Elements Reference Table
| Element | Description | Typical Uses |
|---|---|---|
<header> | Introductory content | Page headers, article headers |
<nav> | Navigation links | Menus, breadcrumbs, pagination |
<main> | Primary content | Main content area (only one per page) |
<section> | Thematic grouping | Chapters, parts, categories |
<article> | Self-contained content | Blog posts, news, comments |
<aside> | Supplementary content | Sidebars, pull quotes, ads |
<footer> | Footer information | Copyright, links, contact info |
<details> | Expandable content | FAQs, collapsible sections |
<summary> | Heading for <details> | Toggle labels |
Best Practices
โ Do This:
<!-- Use header for introductory content -->
<header>
<h1>Blog Title</h1>
</header>
<!-- Use nav for navigation -->
<nav>
<ul>
<li><a href="/">Home</a></li>
</ul>
</nav>
<!-- Use main for primary content (only once) -->
<main>
<article>
<h2>Article Title</h2>
<p>Content...</p>
</article>
</main>
<!-- Use aside for related content -->
<aside>
<h3>Related</h3>
<ul>
<li><a href="#">Link</a></li>
</ul>
</aside>
<!-- Use footer at the bottom -->
<footer>
<p>© 2024 My Site</p>
</footer>
โ Don’t Do This:
<!-- Don't use div when semantic elements exist -->
<div class="header">Header</div>
<!-- Don't use multiple main elements -->
<main>Content 1</main>
<main>Content 2</main> <!-- Invalid -->
<!-- Don't put everything in one section -->
<section>
<h1>Title</h1>
<p>Content</p>
<nav>Navigation</nav> <!-- This belongs outside -->
<footer>Footer</footer> <!-- This belongs outside -->
</section>
<!-- Don't use aside for unrelated content -->
<aside>
<h2>Main Article</h2> <!-- This should be in main -->
<p>...</p>
</aside>
When to Use Semantic Elements
| Scenario | Recommended Element |
|---|---|
| Page header with logo and navigation | <header> |
| Main navigation menu | <nav> |
| Primary page content | <main> |
| Group of related articles | <section> |
| Individual blog post | <article> |
| Sidebar with related links | <aside> |
| Page footer with copyright | <footer> |
| Expandable FAQ section | <details> |
Pro Tip: Using semantic elements is not just about accessibility โ it also improves your website’s SEO. Search engines give more weight to content inside semantic elements like <article> and <main>. Always prefer semantic elements over <div> and <span> when the content has meaning!
18. code, var, kbd, samp, and pre Elements
These elements are used to display technical content, code, keyboard inputs, variables, and sample output in a semantically meaningful way. They are essential for technical documentation, programming tutorials, and educational content.
Overview of Technical Elements
| Element | Purpose | Typical Use |
|---|---|---|
<code> | Represents a fragment of computer code | Inline code snippets, programming examples |
<var> | Represents a variable in mathematics or programming | Variables in equations, programming expressions |
<kbd> | Represents user keyboard input | Keyboard shortcuts, commands to type |
<samp> | Represents sample output from a program | Program output, error messages, examples |
<pre> | Represents preformatted text | Code blocks, preserving whitespace and line breaks |
1. The Code Element <code>
The <code> element indicates that its content should be treated as computer code.
Basic Syntax:
<p>Here is some <code>HTML</code> code:</p>
Browser Display:
Here is some HTML code:
Key Points:
- Used for inline code snippets
- Rendered in a monospace font by default
- Preserves whitespace only when inside a
<pre>element - Can be used for any programming language
Examples:
<p>The <code>console.log()</code> function outputs text to the console.</p>
<p>Use the <code><html></code> tag to start an HTML document.</p>
<p>In Python, <code>print("Hello")</code> displays text.</p>
2. The Variable Element <var>
The <var> element represents a variable in a mathematical equation or programming expression.
Basic Syntax:
<p>2 + <var>x</var> = <math>2 + x</math></p>
Browser Display:
2 + x = 2 + x
Key Points:
- Rendered in italic by default
- Used for mathematical variables and programming variables
- Can be used with
<math>for complex equations
Examples:
<p>The equation is <var>E</var> = <var>mc</var><sup>2</sup></p>
<p>In JavaScript, <var>result</var> = <var>a</var> + <var>b</var></p>
<p>Solve for <var>x</var> in the equation 2<var>x</var> + 5 = 13</p>
3. The Keyboard Element <kbd>
The <kbd> element represents keyboard input โ keys the user should press.
Basic Syntax:
<p>To save your progress, press <kbd>Ctrl</kbd> + <kbd>S</kbd></p>
Browser Display:
To save your progress, press Ctrl + S
Key Points:
- Represents user keyboard input
- Rendered in a monospace font by default (often with a key-like appearance)
- Can be styled to look like physical keys
Examples:
<p>Press <kbd>Enter</kbd> to submit the form.</p>
<p>Use <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy text.</p>
<p>In the terminal, type <kbd>npm install</kbd> and press <kbd>Enter</kbd>.</p>
<p>For undo, press <kbd>Ctrl</kbd> + <kbd>Z</kbd> (Windows) or <kbd>Cmd</kbd> + <kbd>Z</kbd> (Mac).</p>
4. The Sample Element <samp>
The <samp> element represents sample output from a program or system.
Basic Syntax:
<samp>The quick brown fox jumps over the lazy dog.</samp>
Browser Display:The quick brown fox jumps over the lazy dog.
Key Points:
- Represents sample output, error messages, or program results
- Rendered in monospace font by default
- Used to show what the user should expect to see
Examples:
<p>If the installation is successful, you should see:</p>
<samp>Installation complete. (100%)</samp>
<p>When the command fails, you might see:</p>
<samp>Error: File not found: "config.json"</samp>
<p>The program will output:</p>
<samp>Hello, World!<br>Press any key to continue...</samp>
5. The Preformatted Element <pre>
The <pre> element represents preformatted text that preserves whitespace and line breaks exactly as written.
Basic Syntax:
<pre>
<code>
// this is JavaScript
function add(x, y) {
return x + y;
}
</code>
</pre>
Browser Display:
// this is JavaScript
function add(x, y) {
return x + y;
}
Key Points:
- Preserves whitespace, line breaks, and indentation
- Rendered in a monospace font by default
- Often used with
<code>to display code blocks - Maintains the exact formatting of the text
Examples:
<pre>
.container {
display: flex;
justify-content: center;
align-items: center;
}
</pre>
<pre>
#!/bin/bash
echo "Hello, World!"
</pre>
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>code, var, kbd, samp, and pre Elements</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.example-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin: 15px 0;
}
/* ====== CODE STYLES ====== */
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
pre code {
background: none;
padding: 0;
color: inherit;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 20px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.95em;
line-height: 1.8;
}
.language-html .tag { color: #569cd6; }
.language-html .attribute { color: #9cdcfe; }
.language-html .value { color: #ce9178; }
.language-javascript .keyword { color: #c586c0; }
.language-javascript .function { color: #dcdcaa; }
.language-javascript .string { color: #ce9178; }
.language-javascript .comment { color: #6a9955; }
.language-javascript .number { color: #b5cea8; }
/* ====== KBD STYLES ====== */
kbd {
background: #f4f4f4;
padding: 3px 10px;
border-radius: 4px;
border: 1px solid #ccc;
border-bottom: 3px solid #999;
font-family: 'Courier New', monospace;
font-size: 0.95em;
box-shadow: 0 2px 0 #bbb;
background: linear-gradient(to bottom, #f9f9f9, #e9e9e9);
}
/* ====== VAR STYLES ====== */
var {
font-style: italic;
color: #007bff;
font-weight: bold;
}
/* ====== SAMP STYLES ====== */
samp {
font-family: 'Courier New', monospace;
background: #2d2d2d;
color: #4ec9b0;
padding: 2px 8px;
border-radius: 4px;
display: inline-block;
}
/* ====== TABLE ====== */
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.reference-table tr:hover {
background: #e9ecef;
}
</style>
</head>
<body>
<h1>Technical Elements: code, var, kbd, samp, pre</h1>
<!-- ====== SECTION 1: CODE ====== -->
<h2>1. The code Element</h2>
<div class="example-box">
<h3>Inline Code:</h3>
<p>
The <code>console.log()</code> function outputs text to the browser console.
</p>
<p>
Use the <code><html></code> tag to start an HTML document.
</p>
<p>
In Python, <code>print("Hello, World!")</code> displays text.
</p>
<h3>Code with Preformatted Block:</h3>
<pre>
<code>
// This is a JavaScript function
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("World");
</code>
</pre>
</div>
<!-- ====== SECTION 2: VAR ====== -->
<h2>2. The var Element</h2>
<div class="example-box">
<h3>Mathematical Variables:</h3>
<p>
The quadratic formula: <var>x</var> = (-<var>b</var> ยฑ โ(<var>b</var>ยฒ - 4<var>ac</var>)) / 2<var>a</var>
</p>
<p>
Einstein's equation: <var>E</var> = <var>m</var><var>c</var>ยฒ
</p>
<h3>Programming Variables:</h3>
<p>
In JavaScript: <var>result</var> = <var>a</var> + <var>b</var>
</p>
<p>
In Python: <var>total</var> = <var>price</var> * <var>quantity</var>
</p>
<p>
In HTML: <var>element</var> = document.getElementById("<var>id</var>")
</p>
</div>
<!-- ====== SECTION 3: KBD ====== -->
<h2>3. The kbd Element</h2>
<div class="example-box">
<h3>Keyboard Shortcuts:</h3>
<p>
To save your file, press <kbd>Ctrl</kbd> + <kbd>S</kbd>
</p>
<p>
To copy text, press <kbd>Ctrl</kbd> + <kbd>C</kbd>
</p>
<p>
To paste text, press <kbd>Ctrl</kbd> + <kbd>V</kbd>
</p>
<p>
To undo, press <kbd>Ctrl</kbd> + <kbd>Z</kbd>
</p>
<h3>Mac Shortcuts:</h3>
<p>
To save: <kbd>Cmd</kbd> + <kbd>S</kbd>
</p>
<p>
To copy: <kbd>Cmd</kbd> + <kbd>C</kbd>
</p>
<p>
To paste: <kbd>Cmd</kbd> + <kbd>V</kbd>
</p>
<h3>Terminal Commands:</h3>
<p>
In the terminal, type <kbd>npm install</kbd> and press <kbd>Enter</kbd>
</p>
<p>
To list files: <kbd>ls -la</kbd>
</p>
<p>
To change directory: <kbd>cd project-folder</kbd>
</p>
</div>
<!-- ====== SECTION 4: SAMP ====== -->
<h2>4. The samp Element</h2>
<div class="example-box">
<h3>Program Output:</h3>
<p>
If the installation is successful, you should see:
</p>
<samp>Installation complete. (100%)</samp>
<br><br>
<p>
When the command runs successfully:
</p>
<samp>Building project...<br>โ Build completed in 2.3 seconds</samp>
<h3>Error Messages:</h3>
<p>
If the file is missing, you might see:
</p>
<samp style="color: #f48771;">Error: File not found: "config.json"</samp>
<br><br>
<p>
If there's a syntax error:
</p>
<samp style="color: #f48771;">SyntaxError: Unexpected token '}' at line 15</samp>
</div>
<!-- ====== SECTION 5: PRE ====== -->
<h2>5. The pre Element</h2>
<div class="example-box">
<h3>HTML Code Block:</h3>
<pre>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
</pre>
<h3>CSS Code Block:</h3>
<pre>
.container {
display: flex;
justify-content: center;
align-items: center;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.button {
background: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.button:hover {
background: #0056b3;
}
</pre>
<h3>JavaScript Code Block:</h3>
<pre>
// This function calculates the factorial of a number
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// Test the function
const result = factorial(5);
console.log("Factorial of 5 is:", result); // Output: 120
</pre>
<h3>Python Code Block:</h3>
<pre>
# This is a Python script
def greet(name):
return f"Hello, {name}!"
def main():
user_name = input("Enter your name: ")
print(greet(user_name))
if __name__ == "__main__":
main()
</pre>
</div>
<!-- ====== SECTION 6: COMBINED EXAMPLES ====== -->
<h2>6. Combined Examples</h2>
<div class="example-box">
<h3>Programming Tutorial:</h3>
<p>
To create a new variable in JavaScript, use the <code>let</code> or <code>const</code> keyword:
</p>
<pre>
<code>
// Declare a variable
let <var>name</var> = "John";
const <var>age</var> = 25;
// Output to console
console.log(<var>name</var> + " is " + <var>age</var> + " years old.");
</code>
</pre>
<p>
Press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd> to open the browser console.
</p>
<p>
You should see the output:
</p>
<samp>John is 25 years old.</samp>
<h3>Terminal Session:</h3>
<pre>
<samp>$</samp> <kbd>git init</kbd>
<samp>Initialized empty Git repository in /project/.git/</samp>
<samp>$</samp> <kbd>git add .</kbd>
<samp>$</samp> <kbd>git commit -m "Initial commit"</kbd>
<samp>[master (root-commit) a1b2c3d] Initial commit</samp>
<samp> 5 files changed, 120 insertions(+)</samp>
</pre>
</div>
<!-- ====== SECTION 7: REFERENCE TABLE ====== -->
<h2>7. Quick Reference</h2>
<table class="reference-table">
<thead>
<tr>
<th>Element</th>
<th>Purpose</th>
<th>Example</th>
<th>Default Style</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><code></code></td>
<td>Computer code</td>
<td><code>console.log()</code></td>
<td>Monospace</td>
</tr>
<tr>
<td><code><var></code></td>
<td>Variable</td>
<td><var>x</var> = 5</td>
<td>Italic</td>
</tr>
<tr>
<td><code><kbd></code></td>
<td>Keyboard input</td>
<td><kbd>Ctrl</kbd> + <kbd>S</kbd></td>
<td>Monospace + border</td>
</tr>
<tr>
<td><code><samp></code></td>
<td>Sample output</td>
<td><samp>Hello, World!</samp></td>
<td>Monospace</td>
</tr>
<tr>
<td><code><pre></code></td>
<td>Preformatted text</td>
<td><pre>Line 1\nLine 2</pre></td>
<td>Monospace, preserves whitespace</td>
</tr>
</tbody>
</table>
</body>
</html>
Quick Reference
| Element | Purpose | Default Style | When to Use |
|---|---|---|---|
<code> | Code fragment | Monospace | Inline code snippets, programming examples |
<var> | Variable | Italic | Mathematical equations, programming variables |
<kbd> | Keyboard input | Monospace + key style | Keyboard shortcuts, terminal commands |
<samp> | Sample output | Monospace | Program output, error messages |
<pre> | Preformatted text | Monospace, preserves whitespace | Code blocks, formatted text |
Best Practices
โ Do This:
<!-- Use code for inline code -->
<p>Use <code>console.log()</code> to debug.</p>
<!-- Use var for variables -->
<p>Solve for <var>x</var> in the equation.</p>
<!-- Use kbd for keyboard shortcuts -->
<p>Press <kbd>Ctrl</kbd> + <kbd>Enter</kbd> to submit.</p>
<!-- Use samp for output -->
<p>You should see: <samp>Success!</samp></p>
<!-- Use pre for code blocks -->
<pre>
<code>
function add(a, b) {
return a + b;
}
</code>
</pre>
โ Don’t Do This:
<!-- Don't use code for regular text -->
<p><code>This is just regular text</code></p>
<!-- Don't use var for bold/italic styling -->
<p><var>This is not a variable</var></p>
<!-- Don't use kbd for regular text -->
<p><kbd>This is not a keyboard key</kbd></p>
<!-- Don't use samp for regular text -->
<p><samp>This is not sample output</samp></p>
<!-- Don't use pre for everything -->
<pre>
<p>This is regular text but wrapped in pre.</p>
</pre>
Styling Tips
/* Make code look like code */
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
}
/* Make keyboard keys look like keys */
kbd {
background: linear-gradient(to bottom, #f9f9f9, #e9e9e9);
padding: 3px 10px;
border-radius: 4px;
border: 1px solid #ccc;
border-bottom: 3px solid #999;
font-family: 'Courier New', monospace;
box-shadow: 0 2px 0 #bbb;
}
/* Make variables stand out */
var {
font-style: italic;
color: #007bff;
font-weight: bold;
}
/* Style sample output */
samp {
font-family: 'Courier New', monospace;
background: #2d2d2d;
color: #4ec9b0;
padding: 2px 8px;
border-radius: 4px;
}
/* Style code blocks */
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 20px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
line-height: 1.8;
}
Pro Tip: Combine these elements for technical documentation:
<p>
To run the program, type <kbd>node app.js</kbd> in the terminal.
The <var>output</var> variable will contain:
<samp>Hello, World!</samp>
</p>
<pre>
<code>
// Source code
const output = "Hello, World!";
console.log(output);
</code>
</pre>
19 – Entities, Symbols and Emojis in HTML
Entities and symbols
< less than (<) <br>
> greater than (>) <br>
& ampersand (&) <br>
" quotation mark (") <br>
' apostrophe (') <br>
é Euro currency symbol (โฌ) <br>
£ pound sterling symbol (ยฃ) <br>
¢ cent symbol (ยข) <br>
¤ currency symbol (ยค) <br>
¥ yen symbol (ยฅ) <br>
™ trademark symbol (โข) <br>
® registered trademark symbol (ยฎ) <br>
© copyright symbol (ยฉ) <br>
&iexacute; soft hyphen (-) <br>
§ section symbol (ยง) <br>
¶ paragraph symbol (ยถ) <br>
‐ en dash (โ) <br>
‰ per mille sign (โฐ) <br>
× times symbol (ร) <br>
÷ division symbol (รท) <br>
+ plus sign (+) <br>
− minus sign (-) <br>
· middle dot (ยท) <br>
² superscript two (ยฒ) <br>
³ superscript three (ยณ) <br>
´ acute accent (รก รฉ รญ รณ รบ) <br>
á acute accent (ร รจ รฌ รฎ รฒ รบ) <br>
é acute accent (รฉ รข รช รซ รฏ รฎ รด รผ) <br>
ó acute accent (รด รป) <br>
ú acute accent (รบ รป) <br>
ć acute accent (รง ร) <br>
é acute accent (รจ รข รช รซ รฏ รฎ รด รผ) <br>
ú acute accent (รน รบ รป) <br>
ć acute accent (รง ร) <br>
ŕ acute accent (ล ล) <br>
&cuml; cumulus sign (โซ) <br>
&summation; summation sign (โ) <br>
∏ product sign (โ) <br>
√ radical symbol (โ) <br>
&divisionslash; fraction slash (รท) <br>
&fraction; fraction symbol (ยฝ ยพ) <br>
∫ integral sign (โซ) <br>
∴ therefore symbol (therefore) <br>
∼ not equal to (โ) <br>
⊂ subset of (โ) <br>
⊃ superset of (โ) <br>
⊄ not a subset of (โ) <br>
⊆ subset of or equal to (โ) <br>
⊇ superset of or equal to (โ) <br>
¬ logical NOT operator (!) <br>
∀ for all (โ) <br>
&exists; there exists (โ) <br>
- Entity is a way to represent special characters or symbols that are reserved from HTML or not available on all systems
- You can also define custom entities like
Emojis
<meta charset="utf-8">
<p>😂 Hello! (wave)</p>
<p>😎 Smiling face with smiling eyes</p>
<p>😀 Beaming face with smiling eyes</p>
<p>😶 Face with rolling eyes</p>
<p>🤦 Thinking face</p>
<p>🥊 Nerdy face with monocle and lab coat</p>
<p>🎍 Performing arts</p>
<p>🎭 Palette with paintbrush and roll of paper</p>
<p>🚲 Muscle man flexing</p>
<p>🚀 Rocket ship</p>
<p>🌄 Globe with meridians of longitude</p>
<p>🌟 Sun with rays</p>
<p>🌭 Waning crescent moon</p>
<p>🥉 Pine tree in fall colors</p>
<p>🚁 Person skating on ice</p>
<p>🎅 Gift with ribbon</p>
<p>✃ Opening gift</p>
<p>🥪 Closed book with curling corners</p>
<p>🙋 Broken heart</p>
<p>🥵 Face blowing a kiss</p>
<p>🍳 Sleeping face</p>
<p>😍 Person frowning</p>
<p>🤨 Angry face with clenched teeth and upraised eyebrows</p>
<p>🤧 Disappointed but not completely defeated face</p>
<p>🙂 Confused but trying to understand face</p>
<p>🧓 Face with symbol over eyes</p>
<p>🤒 Thinking face with raised eyebrows and hand on chin</p>
<p>🙈 Zipper-mouthed face</p>
<p>😷 Unamused or unimpressed face</p>
<p>😭 Crystal ball weeping face</p>
<p>🧨 Person in a lotus position</p>
<p>🙊 Man lifting a heavy weight</p>
<p>🏀 Person doing acrobatics</p>
<p>🏊 Motion picture camera</p>
<p>🎞 Television with power button turned on</p>
<p>📧 Telephone receiver</p>
<p>🥋 Magnifying glass</p>
<p>🏅 Stage with curtains and stage lights</p>
<p>👝 Movie ticket stubs</p>
<p>🍻 Person with popcorn in their hands</p>
<p>🏀 Pine tree during the winter season</p>
<p>🎅 Person riding a skateboard</p>
<p>🚎 Gymnast doing handstands</p>
<p>👌 Woman gesturing with both hands</p>
<p>🚂 Man lifting a heavy weight</p>
<p>🧗 Girl and boy hugging</p>
<p>🌈 Cherry blossom tree in full bloom</p>
<p>🝒 Evergreen tree with snow on its branches</p>
<p>🍊 Tree with autumn foliage</p>
20. Forms Introduction
Forms are one of the most important features of HTML. They allow users to input data, make selections, and submit information to a server for processing. From login pages to contact forms, search boxes to file uploads, forms power interactivity on the web.
What is an HTML Form?
An HTML form is a container for user input elements like text fields, checkboxes, radio buttons, dropdowns, and buttons. When a user fills out a form and clicks the submit button, the data is sent to a server for processing.
Basic Syntax:
<form action="/submit-form" method="post" autocomplete="on" target="_blank" novalidate enctype="multipart/form-data">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<button type="submit">Submit</button>
</form>
Form Elements Overview
| Element | Purpose | Example |
|---|---|---|
<form> | Container for form controls | <form action="/submit">...</form> |
<input> | User input field | <input type="text" name="username"> |
<label> | Text label for form controls | <label for="name">Name:</label> |
<button> | Clickable button | <button type="submit">Submit</button> |
Form Attributes
Action Attribute action
Specifies the URL where the form data will be sent for processing.
<form action="/submit-form">
| Value | Description |
|---|---|
/submit-form | Relative URL on the same site |
https://example.com/process | Absolute URL to an external server |
# | Submits to the current page |
| Empty or omitted | Submits to the current page URL |
Method Attribute method
Specifies the HTTP method to use when submitting the form.
| Method | Description | Use Case |
|---|---|---|
GET | Data is appended to the URL as a query string | Search forms, non-sensitive data |
POST | Data is sent in the request body (hidden) | Login forms, file uploads, sensitive data |
GET Method Example:
<form action="/search" method="get">
<input type="text" name="q" value="html">
<!-- URL becomes: /search?q=html -->
</form>
POST Method Example:
<form action="/submit" method="post">
<input type="text" name="username">
<!-- Data is sent in the request body, not visible in URL -->
</form>
| Feature | GET | POST |
|---|---|---|
| Data visibility | Visible in URL | Hidden in request body |
| Data size limit | Limited (~2048 characters) | Much larger |
| Security | Less secure (data in URL) | More secure |
| Caching | Can be cached | Not cached |
| Bookmarkable | Yes | No |
| File uploads | Not supported | Supported |
Target Attribute target
Specifies where to display the response after form submission.
<form action="/submit" target="_blank">
| Value | Description |
|---|---|
_self | Opens in the same tab/window (default) |
_blank | Opens in a new tab/window |
_parent | Opens in the parent frame |
_top | Opens in the full body of the window |
framename | Opens in a specific iframe |
Autocomplete Attribute autocomplete
Enables or disables the browser’s autocomplete feature.
<form autocomplete="on"> <!-- Default -->
<form autocomplete="off"> <!-- Disabled -->
on(default): Browser can auto-fill form fieldsoff: Browser cannot auto-fill form fields
Novalidate Attribute novalidate
Disables browser validation on form submission.
<form novalidate>
- Useful when you want to handle validation with JavaScript instead
- Works with
required,pattern,min,max, etc.
Enctype Attribute enctype
Specifies how form data should be encoded when sent to the server.
<form enctype="multipart/form-data">
| Value | Description | Use Case |
|---|---|---|
application/x-www-form-urlencoded | Default โ data is URL-encoded | Regular forms |
multipart/form-data | Data is sent as separate parts | File uploads |
text/plain | Data is sent as plain text | Debugging |
Important: enctype must only be used with method="post".
Form Controls
Label Element <label>
The <label> element provides a text description for a form control.
<label for="name">Name:</label>
<input type="text" id="name" name="name">
Key Points:
- The
forattribute associates the label with an input - The
forvalue must match the input’sid - Clicking the label focuses the input field
- Screen readers read out the label text
Benefits:
- โ Improves accessibility
- โ Increases usability (larger click area)
- โ Better SEO
Input Element <input>
The <input> element is the most commonly used form element. It can create various types of controls by modifying the type attribute.
<input type="text" id="name" name="name">
Common type Attributes:
| Type | Purpose | Example |
|---|---|---|
text | Single-line text input | <input type="text" name="username"> |
email | Email address | <input type="email" name="email"> |
password | Password field | <input type="password" name="password"> |
number | Numeric input | <input type="number" name="age"> |
checkbox | Toggle checkbox | <input type="checkbox" name="agree"> |
radio | Radio button | <input type="radio" name="gender" value="male"> |
submit | Submit button | <input type="submit" value="Send"> |
file | File upload | <input type="file" name="file"> |
date | Date picker | <input type="date" name="birthday"> |
hidden | Hidden field | <input type="hidden" name="token" value="123"> |
Button Element <button>
The <button> element creates a clickable button with various purposes.
<button type="submit">Submit</button>
| Type | Description |
|---|---|
submit | Submits the form data |
reset | Resets all form fields to default values |
button | Generic button (used with JavaScript) |
Examples:
<button type="submit">Save Changes</button>
<button type="reset">Clear Form</button>
<button type="button" onclick="alert('Hello!')">Click Me</button>
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Forms Introduction</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.form-container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-weight: 600;
margin-bottom: 5px;
color: #333;
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="number"],
input[type="date"],
input[type="url"],
select,
textarea {
width: 100%;
padding: 10px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 1em;
transition: border-color 0.3s;
box-sizing: border-box;
}
input:focus,
select:focus,
textarea:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
}
button {
background: #007bff;
color: white;
padding: 12px 30px;
border: none;
border-radius: 6px;
font-size: 1em;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
button[type="reset"] {
background: #6c757d;
margin-left: 10px;
}
button[type="reset"]:hover {
background: #545b62;
}
.btn-group {
margin-top: 20px;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.inline-fields {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.inline-fields .form-group {
flex: 1;
min-width: 200px;
}
.checkbox-group,
.radio-group {
display: flex;
gap: 20px;
flex-wrap: wrap;
align-items: center;
}
.checkbox-group label,
.radio-group label {
display: inline;
font-weight: normal;
margin-right: 10px;
}
.checkbox-group input,
.radio-group input {
margin-right: 5px;
}
textarea {
resize: vertical;
min-height: 100px;
}
</style>
</head>
<body>
<h1>HTML Forms Introduction</h1>
<p>Forms are essential for collecting user input and submitting data to servers.</p>
<!-- ====== SECTION 1: BASIC FORM ====== -->
<h2>1. Basic Form</h2>
<div class="form-container">
<form action="/submit-form" method="post" autocomplete="on" target="_blank" novalidate enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="your@email.com">
</div>
<div class="btn-group">
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>
</form>
</div>
<div class="example-box">
<h4>๐ Form Attributes Explained:</h4>
<ul>
<li><code>action="/submit-form"</code> โ Data is sent to <code>/submit-form</code></li>
<li><code>method="post"</code> โ Data is sent in the request body (hidden)</li>
<li><code>autocomplete="on"</code> โ Browser can suggest auto-fill</li>
<li><code>target="_blank"</code> โ Response opens in a new tab</li>
<li><code>novalidate</code> โ Browser validation is disabled</li>
<li><code>enctype="multipart/form-data"</code> โ Used for file uploads</li>
</ul>
</div>
<hr>
<!-- ====== SECTION 2: METHOD COMPARISON ====== -->
<h2>2. GET vs POST Methods</h2>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<!-- GET Form -->
<div style="flex: 1; min-width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
<h3 style="color: #007bff;">GET Method</h3>
<form action="/search" method="get" style="margin: 0;">
<div class="form-group">
<label for="search">Search:</label>
<input type="text" id="search" name="q" placeholder="Search..." value="html">
</div>
<button type="submit">Search</button>
</form>
<p style="font-size: 0.9em; color: #6c757d; margin-top: 10px;">
๐ Data appears in URL: <code>?q=html</code>
</p>
</div>
<!-- POST Form -->
<div style="flex: 1; min-width: 300px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
<h3 style="color: #28a745;">POST Method</h3>
<form action="/submit" method="post" style="margin: 0;">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter password">
</div>
<button type="submit">Login</button>
</form>
<p style="font-size: 0.9em; color: #6c757d; margin-top: 10px;">
๐ Data is hidden in the request body
</p>
</div>
</div>
<hr>
<!-- ====== SECTION 3: FORM CONTROLS ====== -->
<h2>3. Form Controls</h2>
<div class="form-container">
<form action="#" method="post">
<!-- Text Input -->
<div class="form-group">
<label for="text-input">Text Input:</label>
<input type="text" id="text-input" name="text-input" placeholder="Enter text">
</div>
<!-- Email Input -->
<div class="form-group">
<label for="email-input">Email Input:</label>
<input type="email" id="email-input" name="email-input" placeholder="your@email.com">
</div>
<!-- Password Input -->
<div class="form-group">
<label for="password-input">Password Input:</label>
<input type="password" id="password-input" name="password-input" placeholder="Enter password">
</div>
<!-- Number Input -->
<div class="form-group">
<label for="number-input">Number Input:</label>
<input type="number" id="number-input" name="number-input" placeholder="Enter a number" min="1" max="100">
</div>
<!-- Date Input -->
<div class="form-group">
<label for="date-input">Date Input:</label>
<input type="date" id="date-input" name="date-input">
</div>
<!-- File Upload -->
<div class="form-group">
<label for="file-input">File Upload:</label>
<input type="file" id="file-input" name="file-input">
</div>
<!-- Checkbox -->
<div class="form-group">
<label>Checkbox:</label>
<div class="checkbox-group">
<label>
<input type="checkbox" name="interests" value="html"> HTML
</label>
<label>
<input type="checkbox" name="interests" value="css"> CSS
</label>
<label>
<input type="checkbox" name="interests" value="js"> JavaScript
</label>
</div>
</div>
<!-- Radio Buttons -->
<div class="form-group">
<label>Radio Buttons:</label>
<div class="radio-group">
<label>
<input type="radio" name="gender" value="male"> Male
</label>
<label>
<input type="radio" name="gender" value="female"> Female
</label>
<label>
<input type="radio" name="gender" value="other"> Other
</label>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label for="message">Textarea:</label>
<textarea id="message" name="message" placeholder="Enter your message..." rows="4"></textarea>
</div>
<!-- Select Dropdown -->
<div class="form-group">
<label for="country">Select Dropdown:</label>
<select id="country" name="country">
<option value="">Select a country</option>
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
<option value="ca">Canada</option>
<option value="au">Australia</option>
</select>
</div>
<!-- Hidden Input -->
<input type="hidden" name="token" value="abc123">
<!-- Buttons -->
<div class="btn-group">
<button type="submit">Submit Form</button>
<button type="reset">Reset Form</button>
<button type="button" onclick="alert('Button clicked!')">Alert Button</button>
</div>
</form>
</div>
<hr>
<!-- ====== SECTION 4: REFERENCE TABLE ====== -->
<h2>4. Quick Reference</h2>
<h3>Form Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>action</code></td>
<td>URL to send form data</td>
<td><code>action="/submit"</code></td>
</tr>
<tr>
<td><code>method</code></td>
<td>HTTP method (GET / POST)</td>
<td><code>method="post"</code></td>
</tr>
<tr>
<td><code>target</code></td>
<td>Where to display response</td>
<td><code>target="_blank"</code></td>
</tr>
<tr>
<td><code>autocomplete</code></td>
<td>Enable/disable auto-fill</td>
<td><code>autocomplete="on"</code></td>
</tr>
<tr>
<td><code>novalidate</code></td>
<td>Disable validation</td>
<td><code>novalidate</code></td>
</tr>
<tr>
<td><code>enctype</code></td>
<td>Data encoding for POST</td>
<td><code>enctype="multipart/form-data"</code></td>
</tr>
</tbody>
</table>
<h3>Button Types</h3>
<table class="reference-table">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>submit</code></td>
<td>Submits the form</td>
<td><code><button type="submit"></code></td>
</tr>
<tr>
<td><code>reset</code></td>
<td>Resets form fields</td>
<td><code><button type="reset"></code></td>
</tr>
<tr>
<td><code>button</code></td>
<td>Generic button (JS)</td>
<td><code><button type="button"></code></td>
</tr>
</tbody>
</table>
<hr>
<!-- ====== SECTION 5: BEST PRACTICES ====== -->
<h2>5. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Always use <code><label></code> with <code>for</code> for accessibility</li>
<li>Use <code>method="post"</code> for sensitive data and file uploads</li>
<li>Use <code>method="get"</code> for search forms and bookmarks</li>
<li>Use <code>autocomplete="on"</code> to help users</li>
<li>Use <code>placeholder</code> to provide examples</li>
<li>Group related fields with <code><fieldset></code> and <code><legend></code></li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <code>method="get"</code> for passwords or sensitive data</li>
<li>Don't use <code>method="get"</code> for file uploads</li>
<li>Don't forget the <code>name</code> attribute โ data won't be sent without it!</li>
<li>Don't rely only on browser validation โ always validate on the server</li>
<li>Don't use <code>target="_blank"</code> without <code>rel="noopener"</code></li>
</ul>
</div>
<hr>
<!-- ====== SECTION 6: CODE EXAMPLES ====== -->
<h2>6. Code Examples</h2>
<div style="background: #1e1e1e; color: #d4d4d4; padding: 20px; border-radius: 8px; overflow-x: auto; font-family: 'Courier New', monospace; line-height: 1.8;">
<h3 style="color: #569cd6; margin-top: 0;">Basic Form:</h3>
<pre style="margin: 0; color: #d4d4d4;">
<span style="color: #569cd6;"><form</span> <span style="color: #9cdcfe;">action</span>=<span style="color: #ce9178;">"/submit"</span> <span style="color: #9cdcfe;">method</span>=<span style="color: #ce9178;">"post"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><div></span>
<span style="color: #569cd6;"><label</span> <span style="color: #9cdcfe;">for</span>=<span style="color: #ce9178;">"name"</span><span style="color: #569cd6;">></span>Name:<span style="color: #569cd6;"></label></span>
<span style="color: #569cd6;"><input</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"text"</span> <span style="color: #9cdcfe;">id</span>=<span style="color: #ce9178;">"name"</span> <span style="color: #9cdcfe;">name</span>=<span style="color: #ce9178;">"name"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"></div></span>
<span style="color: #569cd6;"><div></span>
<span style="color: #569cd6;"><label</span> <span style="color: #9cdcfe;">for</span>=<span style="color: #ce9178;">"email"</span><span style="color: #569cd6;">></span>Email:<span style="color: #569cd6;"></label></span>
<span style="color: #569cd6;"><input</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"email"</span> <span style="color: #9cdcfe;">id</span>=<span style="color: #ce9178;">"email"</span> <span style="color: #9cdcfe;">name</span>=<span style="color: #ce9178;">"email"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"></div></span>
<span style="color: #569cd6;"><button</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"submit"</span><span style="color: #569cd6;">></span>Submit<span style="color: #569cd6;"></button></span>
<span style="color: #569cd6;"></form></span>
</pre>
<h3 style="color: #569cd6;">File Upload Form:</h3>
<pre style="margin: 0; color: #d4d4d4;">
<span style="color: #569cd6;"><form</span> <span style="color: #9cdcfe;">action</span>=<span style="color: #ce9178;">"/upload"</span> <span style="color: #9cdcfe;">method</span>=<span style="color: #ce9178;">"post"</span> <span style="color: #9cdcfe;">enctype</span>=<span style="color: #ce9178;">"multipart/form-data"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><label</span> <span style="color: #9cdcfe;">for</span>=<span style="color: #ce9178;">"file"</span><span style="color: #569cd6;">></span>Choose a file:<span style="color: #569cd6;"></label></span>
<span style="color: #569cd6;"><input</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"file"</span> <span style="color: #9cdcfe;">id</span>=<span style="color: #ce9178;">"file"</span> <span style="color: #9cdcfe;">name</span>=<span style="color: #ce9178;">"file"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><button</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"submit"</span><span style="color: #569cd6;">></span>Upload<span style="color: #569cd6;"></button></span>
<span style="color: #569cd6;"></form></span>
</pre>
</div>
</body>
</html>
Quick Reference
| Element/Attribute | Purpose | Example |
|---|---|---|
<form> | Form container | <form action="/submit" method="post"> |
action | Submission URL | action="/submit-form" |
method | HTTP method | method="post" |
target | Response window | target="_blank" |
autocomplete | Auto-fill behavior | autocomplete="on" |
novalidate | Disable validation | novalidate |
enctype | Data encoding | enctype="multipart/form-data" |
<label> | Text label | <label for="name">Name:</label> |
<input> | User input | <input type="text" name="name"> |
<button> | Clickable button | <button type="submit">Send</button> |
Best Practices Checklist
- โ
Always use
<label>withforfor accessibility - โ
Use
method="post"for sensitive data - โ
Use
method="get"for search forms - โ
Use
enctype="multipart/form-data"for file uploads - โ
Always include a
nameattribute on inputs - โ Validate on both client and server
- โ
Use
autocomplete="on"for better UX - โ Add placeholders for user guidance
Pro Tip: Forms are the bridge between users and your application. A well-designed form with proper semantic HTML, accessibility, and validation improves user experience and data quality!
21. Input and Textarea Elements
The <input> and <textarea> elements are the most essential building blocks of HTML forms. They allow users to enter, select, and submit data in various ways. Understanding their different types and attributes is crucial for creating effective and user-friendly forms.
The Input Element <input>
The <input> element is a powerful and versatile form control. Its behavior changes dramatically based on the type attribute, making it suitable for collecting almost any kind of user input.
Basic Structure:
<input type="text" id="name" name="name" placeholder="Your name" required>
Common Attributes:
| Attribute | Purpose | Example |
|---|---|---|
type | Specifies the input type | type="text" |
name | Identifies the input (sent to server) | name="username" |
id | Unique identifier (for labels, JS) | id="username" |
value | Sets a default value | value="John" |
placeholder | Provides a hint or example | placeholder="Enter your name" |
required | Makes the field mandatory | required |
disabled | Disables the input field | disabled |
readonly | Makes the field read-only | readonly |
min / max | Sets minimum/maximum values | min="0" max="100" |
step | Sets the increment step | step="5" |
Input Types
1. Text Input type="text"
Creates a single-line text field that accepts letters, numbers, and symbols.
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Your name" required>
Browser Display:
[ Your name ] (single-line text box)
2. Password Input type="password"
Creates a single-line text field that hides the characters as they are typed.
<label for="password">Password:</label>
<input type="password" id="password" name="password">
Browser Display:
[ โขโขโขโขโขโขโขโข ] (dots replace actual characters)
3. Number Input type="number"
Creates a numeric input field with up/down arrows (spinners).
<label for="age">Age:</label>
<input type="number" id="age" name="age" value="19" min="0" max="120">
Browser Display:
[ 19 โฌโฌ ] (number field with spinners)
4. Date and Time Inputs
Date Input type="date"
<label for="date">Date:</label>
<input type="date" id="date" name="date">
Browser Display:
[ ๐
MM/DD/YYYY ] (date picker)
Time Input type="time"
<label for="time">Time:</label>
<input type="time" id="time" name="time">
Browser Display:
[ โฐ –:– ] (time picker)
DateTime-Local Input type="datetime-local"
<label for="datetime">Date and Time:</label>
<input type="datetime-local" id="datetime" name="datetime">
Browser Display:
[ ๐
MM/DD/YYYY –:– ] (combined picker)
5. Range Input type="range"
Creates a slider control for selecting a value from a range.
<label for="range">Range:</label>
<input type="range" id="range" name="range"
min="0" max="10" step="1" value="9">
Browser Display:
[โโโโโโโโโโโโโโโ] (slider at position 9)
Attributes:
minโ Minimum value (default: 0)maxโ Maximum value (default: 100)stepโ Increment step (default: 1)valueโ Initial position
6. Email Input type="email"
Creates an input field for email addresses with built-in validation.
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="your@email.com">
Browser Display:
[ your@email.com ] (validates email format)
7. URL Input type="url"
Creates an input field for URLs with built-in validation.
<label for="url">Website:</label>
<input type="url" id="url" name="url" placeholder="https://example.com">
Browser Display:
[ https://example.com ] (validates URL format)
8. Hidden Input type="hidden"
Creates an invisible input that stores data to be submitted with the form.
<input type="hidden" name="id" value="1">
Purpose:
- Store data that users don’t need to see or edit (e.g., user ID, session tokens)
- Pass data between pages
9. Checkbox Input type="checkbox"
Creates a toggleable checkbox that allows users to select/deselect an option.
<input type="checkbox" id="option1" name="exampleCheckboxGroup">
<label for="option1">Option 1</label>
<input type="checkbox" id="option2" name="exampleCheckboxGroup">
<label for="option2">Option 2</label>
<input type="checkbox" id="option3" name="exampleCheckboxGroup">
<label for="option3">Option 3</label>
Browser Display:
โ Option 1
โ Option 2
โ Option 3
Key Points:
- Allows multiple selections
- Use the same
namefor group, but each must have a uniquevalue - Checked state sends the
valueto the server
10. Radio Buttons type="radio"
Creates radio buttons that allow users to select only one option from a group.
<input type="radio" id="option1" name="shippingMethod" value="next-day">
<label for="option1">Next-day delivery (extra fee)</label>
<input type="radio" id="option2" name="shippingMethod" value="standard">
<label for="option2">Standard delivery</label>
<input type="radio" id="option3" name="shippingMethod" value="pickup">
<label for="option3">Pick up in store</label>
Browser Display:
โ Next-day delivery (extra fee)
โ Standard delivery
โ Pick up in store
Key Points:
- Allows only one selection per group
- Elements with the same
namebelong to the same group - The selected value is sent to the server
The Textarea Element <textarea>
The <textarea> element creates a multi-line text input for longer text entries.
<label for="userInput">Enter your message:</label>
<textarea id="userInput" name="userInput" rows="4" cols="50"></textarea>
Browser Display:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ โ
โ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
rows | Number of visible text lines | rows="4" |
cols | Width in characters | cols="50" |
maxlength | Maximum number of characters | maxlength="500" |
minlength | Minimum number of characters | minlength="10" |
placeholder | Hint text | placeholder="Type your message..." |
required | Makes the field mandatory | required |
disabled | Disables the textarea | disabled |
readonly | Makes the field read-only | readonly |
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input and Textarea Elements</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.form-container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-weight: 600;
margin-bottom: 5px;
color: #333;
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="number"],
input[type="date"],
input[type="datetime-local"],
input[type="time"],
input[type="url"],
textarea,
select {
width: 100%;
padding: 10px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 1em;
transition: border-color 0.3s;
box-sizing: border-box;
font-family: inherit;
}
input:focus,
textarea:focus,
select:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
}
input[type="range"] {
width: 100%;
padding: 5px 0;
border: none;
}
.checkbox-group,
.radio-group {
display: flex;
flex-wrap: wrap;
gap: 15px;
align-items: center;
padding: 5px 0;
}
.checkbox-group label,
.radio-group label {
display: inline;
font-weight: normal;
margin: 0 5px 0 0;
cursor: pointer;
}
.checkbox-group input,
.radio-group input {
margin-right: 5px;
cursor: pointer;
}
textarea {
resize: vertical;
min-height: 80px;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.btn-group {
margin-top: 20px;
}
button {
background: #007bff;
color: white;
padding: 12px 30px;
border: none;
border-radius: 6px;
font-size: 1em;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
button[type="reset"] {
background: #6c757d;
margin-left: 10px;
}
button[type="reset"]:hover {
background: #545b62;
}
.inline-fields {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.inline-fields .form-group {
flex: 1;
min-width: 200px;
}
.range-value {
font-weight: bold;
color: #007bff;
font-size: 1.2em;
}
.field-demo {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
padding: 10px;
background: #f8f9fa;
border-radius: 6px;
}
</style>
</head>
<body>
<h1>Input and Textarea Elements</h1>
<p>A comprehensive guide to form input types and the textarea element.</p>
<!-- ====== MAIN FORM ====== -->
<div class="form-container">
<form method="post" action="#">
<!-- Hidden Input -->
<input type="hidden" name="id" value="1">
<h2>1. Basic Input Types</h2>
<!-- Text Input -->
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Your full name" required>
<small>Required field โ single-line text</small>
</div>
<!-- Password Input -->
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter a strong password">
<small>Characters are hidden</small>
</div>
<!-- Number Input -->
<div class="form-group">
<label for="age">Age:</label>
<input type="number" id="age" name="age" value="19" min="0" max="120" step="1">
<small>Min: 0, Max: 120</small>
</div>
<hr>
<h2>2. Date and Time Inputs</h2>
<div class="inline-fields">
<!-- Date Input -->
<div class="form-group">
<label for="date">Date:</label>
<input type="date" id="date" name="date">
</div>
<!-- Time Input -->
<div class="form-group">
<label for="time">Time:</label>
<input type="time" id="time" name="time">
</div>
<!-- DateTime-Local Input -->
<div class="form-group">
<label for="datetime">Date and Time:</label>
<input type="datetime-local" id="datetime" name="datetime">
</div>
</div>
<hr>
<h2>3. Range Input</h2>
<div class="form-group">
<label for="range">Range (0 to 10):</label>
<div class="field-demo">
<input type="range" id="range" name="range"
min="0" max="10" step="1" value="9"
oninput="document.getElementById('range-value').textContent = this.value">
<span class="range-value" id="range-value">9</span>
</div>
<small>Slide to select a value</small>
</div>
<hr>
<h2>4. Validation Inputs</h2>
<div class="inline-fields">
<!-- Email Input -->
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="your@email.com">
<small>Validates email format</small>
</div>
<!-- URL Input -->
<div class="form-group">
<label for="url">URL:</label>
<input type="url" id="url" name="url" placeholder="https://example.com">
<small>Validates URL format</small>
</div>
</div>
<hr>
<h2>5. Textarea (Multi-line Input)</h2>
<div class="form-group">
<label for="userInput">Enter your message:</label>
<textarea id="userInput" name="userInput" rows="4" cols="50"
placeholder="Type your message here..."
maxlength="500"></textarea>
<small>Max 500 characters</small>
</div>
<hr>
<h2>6. Checkbox Inputs</h2>
<div class="form-group">
<label>Select your interests (multiple choices):</label>
<div class="checkbox-group">
<input type="checkbox" id="option1" name="interests" value="html">
<label for="option1">HTML</label>
<input type="checkbox" id="option2" name="interests" value="css">
<label for="option2">CSS</label>
<input type="checkbox" id="option3" name="interests" value="js">
<label for="option3">JavaScript</label>
<input type="checkbox" id="option4" name="interests" value="python">
<label for="option4">Python</label>
</div>
<small>You can select multiple options</small>
</div>
<hr>
<h2>7. Radio Buttons</h2>
<div class="form-group">
<label>Select shipping method (choose one):</label>
<div class="radio-group">
<input type="radio" id="shipping1" name="shippingMethod" value="next-day">
<label for="shipping1">Next-day delivery (extra fee)</label>
<input type="radio" id="shipping2" name="shippingMethod" value="standard" checked>
<label for="shipping2">Standard delivery</label>
<input type="radio" id="shipping3" name="shippingMethod" value="pickup">
<label for="shipping3">Pick up in store</label>
</div>
<small>Only one option can be selected</small>
</div>
<div class="btn-group">
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>
</form>
</div>
<!-- ====== REFERENCE TABLE ====== -->
<h2>8. Input Type Reference</h2>
<table class="reference-table">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
<th>Use Case</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>text</code></td>
<td>Single-line text</td>
<td>Names, addresses, general text</td>
</tr>
<tr>
<td><code>password</code></td>
<td>Hidden characters</td>
<td>Passwords, sensitive data</td>
</tr>
<tr>
<td><code>number</code></td>
<td>Numeric input</td>
<td>Age, quantity, price</td>
</tr>
<tr>
<td><code>email</code></td>
<td>Email address</td>
<td>Email fields with validation</td>
</tr>
<tr>
<td><code>url</code></td>
<td>URL input</td>
<td>Website URLs with validation</td>
</tr>
<tr>
<td><code>date</code></td>
<td>Date picker</td>
<td>Birthdays, appointments</td>
</tr>
<tr>
<td><code>time</code></td>
<td>Time picker</td>
<td>Scheduling, time selection</td>
</tr>
<tr>
<td><code>datetime-local</code></td>
<td>Date + time picker</td>
<td>Events, appointments</td>
</tr>
<tr>
<td><code>range</code></td>
<td>Slider control</td>
<td>Volume, rating, price range</td>
</tr>
<tr>
<td><code>checkbox</code></td>
<td>Toggle checkbox</td>
<td>Multiple selections, toggles</td>
</tr>
<tr>
<td><code>radio</code></td>
<td>Radio button</td>
<td>Single selection, gender, shipping</td>
</tr>
<tr>
<td><code>hidden</code></td>
<td>Hidden input</td>
<td>IDs, tokens, session data</td>
</tr>
</tbody>
</table>
<hr>
<!-- ====== COMPARISON: CHECKBOX vs RADIO ====== -->
<h2>9. Checkbox vs Radio Buttons</h2>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<!-- Checkbox Example -->
<div style="flex: 1; min-width: 250px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
<h3 style="color: #007bff;">โ
Checkbox</h3>
<p><small>Multiple selections allowed</small></p>
<div class="checkbox-group">
<input type="checkbox" id="cb1" name="fruits" value="apple">
<label for="cb1">๐ Apple</label>
<input type="checkbox" id="cb2" name="fruits" value="banana">
<label for="cb2">๐ Banana</label>
<input type="checkbox" id="cb3" name="fruits" value="orange">
<label for="cb3">๐ Orange</label>
</div>
</div>
<!-- Radio Example -->
<div style="flex: 1; min-width: 250px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
<h3 style="color: #28a745;">๐ Radio Button</h3>
<p><small>Only one selection allowed</small></p>
<div class="radio-group">
<input type="radio" id="r1" name="fruit" value="apple">
<label for="r1">๐ Apple</label>
<input type="radio" id="r2" name="fruit" value="banana">
<label for="r2">๐ Banana</label>
<input type="radio" id="r3" name="fruit" value="orange">
<label for="r3">๐ Orange</label>
</div>
</div>
</div>
<hr>
<!-- ====== BEST PRACTICES ====== -->
<h2>10. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Always use <code><label></code> with <code>for</code> for accessibility</li>
<li>Use <code>type="email"</code> and <code>type="url"</code> for automatic validation</li>
<li>Use <code>placeholder</code> to provide examples</li>
<li>Use <code>required</code> for mandatory fields</li>
<li>Set appropriate <code>min</code>, <code>max</code>, and <code>step</code> for numeric inputs</li>
<li>Group related radio buttons with the same <code>name</code></li>
<li>Use <code>textarea</code> for longer text entries</li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <code>type="text"</code> for emails, numbers, or dates</li>
<li>Don't forget the <code>name</code> attribute โ data won't be sent without it!</li>
<li>Don't use <code>placeholder</code> as a substitute for labels</li>
<li>Don't rely only on client-side validation โ always validate on the server</li>
<li>Don't use <code>type="number"</code> for phone numbers (use <code>type="tel"</code>)</li>
<li>Don't use <code>type="password"</code> without also using <code>autocomplete="off"</code> in sensitive contexts</li>
</ul>
</div>
</body>
</html>
Quick Reference
| Input Type | Description | Attributes |
|---|---|---|
text | Single-line text | placeholder, maxlength |
password | Hidden text | placeholder, maxlength |
number | Numeric input | min, max, step, value |
email | Email with validation | placeholder, multiple |
url | URL with validation | placeholder |
date | Date picker | min, max, value |
time | Time picker | min, max, step, value |
datetime-local | Date + time picker | min, max, step, value |
range | Slider control | min, max, step, value |
checkbox | Toggle checkbox | checked, value |
radio | Single selection | checked, value |
hidden | Invisible data | value |
Textarea vs Input
| Feature | <textarea> | <input> |
|---|---|---|
| Lines | Multi-line | Single-line |
| Resize | Yes (CSS/User) | No |
| Attributes | rows, cols | size, maxlength |
| Default Content | Between tags | value attribute |
| Use Case | Messages, comments | Short entries |
Pro Tip: Choose the right input type for your data. Using the correct type provides automatic validation, improves user experience on mobile devices, and makes your forms more accessible. Always pair inputs with proper labels for accessibility!
22. select, option, optgroup, legend, fieldset, output Elements
These elements help organize and structure forms, making them more user-friendly and accessible. They allow you to create dropdown lists, group related form controls, and display calculated results.
Overview of Form Structure Elements
| Element | Purpose | Example |
|---|---|---|
<select> | Creates a drop-down list | <select name="country">...</select> |
<option> | Defines an item in a dropdown list | <option value="us">United States</option> |
<optgroup> | Groups related options | <optgroup label="Fruits">...</optgroup> |
<fieldset> | Groups related form controls | <fieldset>...</fieldset> |
<legend> | Caption/title for a fieldset | <legend>Personal Information</legend> |
<output> | Displays calculation results | <output id="result"></output> |
The Select Element <select>
The <select> element creates a drop-down list that allows users to choose one or more options from a list.
Basic Syntax:
<select name="fruits" id="fruits">
<option value="apple">Apple</option>
<option value="banana" selected>Banana</option>
<option value="orange">Orange</option>
</select>
Browser Display:
[ Banana โผ ] (dropdown list showing selected option)
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
name | Identifies the element when submitted | name="country" |
id | Unique identifier for labels and JavaScript | id="country" |
size | Number of visible options | size="3" |
autofocus | Automatically focuses on page load | autofocus |
required | Makes selection mandatory | required |
disabled | Disables the dropdown | disabled |
multiple | Allows multiple selections | multiple |
The Option Element <option>
The <option> element defines an item inside a <select> or <datalist>.
Basic Syntax:
<option value="apple">Apple</option>
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
value | Value sent to the server | value="apple" |
selected | Pre-selects this option | selected |
disabled | Disables this option | disabled |
label | Shorter label for the option | label="Apple" |
Key Points:
- The inner text is displayed to the user
- The value attribute is sent to the server
- If no
valueis provided, the inner text is used as the value
The Optgroup Element <optgroup>
The <optgroup> element groups related <option> elements together with a label.
Basic Syntax:
<optgroup label="Fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
</optgroup>
Browser Display:
Fruits
โโโ Apple
โโโ Banana
Vegetables
โโโ Carrot
โโโ Broccoli
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
label | Group name displayed in the list | label="Fruits" |
disabled | Disables all options in the group | disabled |
The Fieldset Element <fieldset>
The <fieldset> element groups related form controls together, creating a visual boundary around them.
Basic Syntax:
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</fieldset>
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
disabled | Disables all controls inside | disabled |
form | Associates with a specific form | form="myForm" |
name | Identifies the fieldset | name="personal" |
The Legend Element <legend>
The <legend> element provides a caption/title for a <fieldset>.
Basic Syntax:
<fieldset>
<legend>Personal Information</legend>
<!-- Form controls -->
</fieldset>
Browser Display:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Personal Information โ
โ [Name: ] โ
โ [Email: ] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Output Element <output>
The <output> element displays the result of a calculation or user interaction.
Basic Syntax:
<output id="result">0</output>
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
for | Associates with related elements | for="input1 input2" |
name | Identifies the output | name="result" |
form | Associates with a specific form | form="myForm" |
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>select, option, optgroup, fieldset, legend, output</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.form-container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
/* ====== Fieldset Styles ====== */
fieldset {
border: 2px solid #ddd;
border-radius: 8px;
padding: 20px;
margin-bottom: 25px;
background: #fafafa;
transition: border-color 0.3s;
}
fieldset:hover {
border-color: #007bff;
}
legend {
font-size: 1.1em;
font-weight: 700;
color: #007bff;
padding: 0 10px;
background: white;
border-radius: 4px;
}
/* ====== Form Controls ====== */
.form-group {
margin-bottom: 15px;
}
label {
display: block;
font-weight: 600;
margin-bottom: 5px;
color: #333;
}
input[type="text"],
input[type="email"],
input[type="tel"],
select {
width: 100%;
padding: 10px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 1em;
transition: border-color 0.3s;
box-sizing: border-box;
font-family: inherit;
}
input:focus,
select:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
}
select[size] {
height: auto;
}
select[multiple] {
height: 120px;
}
/* ====== Option & Optgroup ====== */
optgroup {
font-weight: 700;
color: #007bff;
}
optgroup option {
font-weight: normal;
color: #333;
padding: 5px 10px;
}
option:checked {
background: #007bff;
color: white;
}
/* ====== Output Styles ====== */
output {
display: inline-block;
font-weight: 700;
font-size: 1.2em;
color: #28a745;
background: #e9f7ed;
padding: 8px 16px;
border-radius: 6px;
border: 1px solid #28a745;
min-width: 60px;
text-align: center;
}
.output-container {
background: #f8f9fa;
padding: 15px;
border-radius: 6px;
text-align: center;
margin: 10px 0;
}
/* ====== Buttons ====== */
.btn-group {
margin-top: 20px;
}
button {
background: #007bff;
color: white;
padding: 12px 30px;
border: none;
border-radius: 6px;
font-size: 1em;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
button[type="reset"] {
background: #6c757d;
margin-left: 10px;
}
button[type="reset"]:hover {
background: #545b62;
}
/* ====== Reference Table ====== */
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.reference-table tr:hover {
background: #e9ecef;
}
/* ====== Code Styles ====== */
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.inline-fields {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.inline-fields .form-group {
flex: 1;
min-width: 200px;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
.highlight {
background: #ffc107;
padding: 2px 6px;
border-radius: 3px;
}
</style>
</head>
<body>
<h1>select, option, optgroup, fieldset, legend, output</h1>
<!-- ====== MAIN FORM ====== -->
<div class="form-container">
<form action="/submit_form" method="post">
<!-- ====== PERSONAL INFORMATION ====== -->
<fieldset>
<legend>๐ค Personal Information</legend>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="your@email.com">
</div>
<div class="form-group">
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone" placeholder="(123) 456-7890">
</div>
</fieldset>
<!-- ====== FRUITS & VEGETABLES ====== -->
<fieldset>
<legend>๐ Fruits and Vegetables</legend>
<div class="form-group">
<label for="fruits">Select your favorite:</label>
<select name="fruits" id="fruits" size="4" autofocus>
<optgroup label="๐ Fruits">
<option value="apple">Apple</option>
<option value="banana" selected>Banana</option>
<option value="orange">Orange</option>
<option value="strawberry">Strawberry</option>
</optgroup>
<optgroup label="๐ฅฌ Vegetables">
<option value="carrot" disabled>Carrot (disabled)</option>
<option value="broccoli">Broccoli</option>
<option value="spinach">Spinach</option>
</optgroup>
</select>
<small>Size: 4 visible options | Autofocus enabled | Carrot is disabled</small>
</div>
</fieldset>
<!-- ====== OUTPUT ====== -->
<div class="form-group">
<label>Result:</label>
<div class="output-container">
<output id="result">0</output>
</div>
</div>
<!-- ====== BUTTONS ====== -->
<div class="btn-group">
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>
</form>
</div>
<!-- ====== SECTION: MORE EXAMPLES ====== -->
<h2>More Examples</h2>
<!-- ====== EXAMPLE 1: SELECT WITH MULTIPLE ATTRIBUTE ====== -->
<div class="form-container">
<h3>1. Select with Multiple Attribute</h3>
<p>Hold <kbd>Ctrl</kbd> (Windows) or <kbd>Cmd</kbd> (Mac) to select multiple options.</p>
<fieldset>
<legend>๐ Select Your Interests</legend>
<select name="interests" id="interests" multiple size="4">
<optgroup label="๐ป Technology">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="js">JavaScript</option>
<option value="python">Python</option>
</optgroup>
<optgroup label="๐จ Design">
<option value="ui">UI Design</option>
<option value="ux">UX Design</option>
<option value="graphic">Graphic Design</option>
</optgroup>
</select>
<small>Multiple selections allowed</small>
</fieldset>
</div>
<!-- ====== EXAMPLE 2: OPTION ATTRIBUTES ====== -->
<div class="form-container">
<h3>2. Option Attributes: selected, disabled, label</h3>
<fieldset>
<legend>๐ท๏ธ Option Attributes Demo</legend>
<div class="form-group">
<label for="status">Select Status:</label>
<select name="status" id="status">
<option value="active" selected>โ
Active (selected)</option>
<option value="inactive" disabled>๐ซ Inactive (disabled)</option>
<option value="pending">โณ Pending</option>
<option value="suspended" disabled>๐ Suspended (disabled)</option>
</select>
<small>Selected and disabled options demonstrated</small>
</div>
</fieldset>
</div>
<!-- ====== EXAMPLE 3: OUTPUT WITH CALCULATION ====== -->
<div class="form-container">
<h3>3. Output with Calculation</h3>
<p>Move the slider to see the <code><output></code> element update in real-time.</p>
<fieldset>
<legend>๐ข Value Calculator</legend>
<div class="form-group">
<label for="slider">Value:</label>
<input type="range" id="slider" name="slider"
min="0" max="100" step="1" value="50"
oninput="document.getElementById('calc-result').value = this.value">
<span id="slider-value" style="font-weight: bold; color: #007bff;">50</span>
</div>
<div class="form-group">
<label>Result (squared):</label>
<div class="output-container">
<output id="calc-result">2500</output>
<small>(value ร value)</small>
</div>
</div>
</fieldset>
</div>
<!-- ====== EXAMPLE 4: NESTED FIELDSETS ====== -->
<div class="form-container">
<h3>4. Nested Fieldsets</h3>
<fieldset>
<legend>๐ข Company Information</legend>
<div class="form-group">
<label for="company">Company Name:</label>
<input type="text" id="company" name="company" placeholder="Enter company name">
</div>
<fieldset style="margin-top: 15px; border-color: #28a745;">
<legend style="color: #28a745;">๐จโ๐ผ Contact Person</legend>
<div class="form-group">
<label for="contact-name">Contact Name:</label>
<input type="text" id="contact-name" name="contact-name" placeholder="Full name">
</div>
<div class="form-group">
<label for="contact-email">Contact Email:</label>
<input type="email" id="contact-email" name="contact-email" placeholder="email@company.com">
</div>
</fieldset>
<div class="form-group" style="margin-top: 15px;">
<label for="department">Department:</label>
<select name="department" id="department">
<optgroup label="๐ข Main Departments">
<option value="it">IT</option>
<option value="hr">Human Resources</option>
<option value="sales">Sales</option>
</optgroup>
<optgroup label="๐๏ธ Other Departments">
<option value="rnd">R&D</option>
<option value="marketing">Marketing</option>
</optgroup>
</select>
</div>
</fieldset>
</div>
<!-- ====== REFERENCE TABLES ====== -->
<h2>Quick Reference</h2>
<h3>Select Element Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>name</code></td>
<td>Identifies the element when submitted</td>
<td><code>name="country"</code></td>
</tr>
<tr>
<td><code>id</code></td>
<td>Unique identifier</td>
<td><code>id="country"</code></td>
</tr>
<tr>
<td><code>size</code></td>
<td>Number of visible options</td>
<td><code>size="3"</code></td>
</tr>
<tr>
<td><code>autofocus</code></td>
<td>Auto-focus on page load</td>
<td><code>autofocus</code></td>
</tr>
<tr>
<td><code>required</code></td>
<td>Mandatory selection</td>
<td><code>required</code></td>
</tr>
<tr>
<td><code>disabled</code></td>
<td>Disables the dropdown</td>
<td><code>disabled</code></td>
</tr>
<tr>
<td><code>multiple</code></td>
<td>Allows multiple selections</td>
<td><code>multiple</code></td>
</tr>
</tbody>
</table>
<h3>Option & Optgroup Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Element</th>
<th>Attribute</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><option></code></td>
<td><code>value</code></td>
<td>Value sent to the server</td>
<td><code>value="apple"</code></td>
</tr>
<tr>
<td><code><option></code></td>
<td><code>selected</code></td>
<td>Pre-selects the option</td>
<td><code>selected</code></td>
</tr>
<tr>
<td><code><option></code></td>
<td><code>disabled</code></td>
<td>Disables the option</td>
<td><code>disabled</code></td>
</tr>
<tr>
<td><code><optgroup></code></td>
<td><code>label</code></td>
<td>Group name displayed</td>
<td><code>label="Fruits"</code></td>
</tr>
</tbody>
</table>
<h3>Fieldset & Legend</h3>
<table class="reference-table">
<thead>
<tr>
<th>Element</th>
<th>Purpose</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><fieldset></code></td>
<td>Groups related form controls</td>
<td><code><fieldset>...</fieldset></code></td>
</tr>
<tr>
<td><code><legend></code></td>
<td>Caption/title for fieldset</td>
<td><code><legend>Title</legend></code></td>
</tr>
<tr>
<td><code><output></code></td>
<td>Displays calculation results</td>
<td><code><output id="result"></output></code></td>
</tr>
</tbody>
</table>
<!-- ====== BEST PRACTICES ====== -->
<h2>Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Use <code><fieldset></code> and <code><legend></code> to <strong>organize</strong> large forms</li>
<li>Use <code><optgroup></code> to <strong>categorize</strong> options in long dropdowns</li>
<li>Use <code>selected</code> to <strong>pre-select</strong> the most common option</li>
<li>Use <code>disabled</code> for <strong>unavailable</strong> options</li>
<li>Use <code><output></code> for <strong>calculated</strong> or dynamic values</li>
<li>Always use <code><label></code> with <code>for</code> for <strong>accessibility</strong></li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <code><optgroup></code> without the <code>label</code> attribute</li>
<li>Don't forget the <code>value</code> attribute on options</li>
<li>Don't use <code><output></code> for static content</li>
<li>Don't use <code>size="1"</code> when you want a dropdown (use default)</li>
<li>Don't use <code>multiple</code> without informing users they can select multiple</li>
</ul>
</div>
</body>
</html>
Quick Reference
| Element | Purpose | Key Attributes |
|---|---|---|
<select> | Drop-down list | name, size, multiple, autofocus |
<option> | List item | value, selected, disabled |
<optgroup> | Group of options | label, disabled |
<fieldset> | Group of form controls | disabled, form |
<legend> | Fieldset caption | (none โ text content only) |
<output> | Calculation result | for, name, form |
Best Practices Checklist
- โ
Use
<fieldset>to group related controls in large forms - โ
Use
<legend>to describe each group - โ
Use
<optgroup>to categorize options in long lists - โ
Pre-select common options with
selected - โ
Use
disabledfor unavailable options - โ
Use
<output>for dynamic results - โ
Always use
<label>withforfor accessibility
Pro Tip: The combination of <fieldset> and <legend> significantly improves form accessibility and usability. Screen readers announce the legend as a group label, helping users understand the context of each input. Use <optgroup> when your dropdown has more than 5 options to improve user experience!
23. video, audio, and source Elements
The <video>, <audio>, and <source> elements allow you to embed multimedia content directly into your web pages without requiring third-party plugins. They provide native playback controls and support for multiple formats.
Overview of Multimedia Elements
| Element | Purpose | Example |
|---|---|---|
<video> | Embeds video content | <video src="video.mp4" controls></video> |
<audio> | Embeds audio content | <audio src="audio.mp3" controls></audio> |
<source> | Specifies media files (multiple formats) | <source src="video.mp4" type="video/mp4"> |
The Video Element <video>
The <video> element embeds video content directly into a webpage, providing native playback controls.
Basic Syntax:
<video controls autoplay width="400" height="300" muted loop>
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
Your browser does not support the video tag.
</video>
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
controls | Shows playback controls (play, pause, volume) | controls |
autoplay | Starts playing automatically | autoplay |
muted | Mutes the audio | muted |
loop | Replays the video when it ends | loop |
width | Sets video width (in pixels) | width="640" |
height | Sets video height (in pixels) | height="360" |
poster | Thumbnail image before playback | poster="thumbnail.jpg" |
preload | Preloads video data | preload="auto" |
playsinline | Plays inline on mobile devices | playsinline |
Supported Video Formats:
| Format | MIME Type | Browser Support |
|---|---|---|
| MP4 (H.264) | video/mp4 | All modern browsers |
| WebM | video/webm | Chrome, Firefox, Edge, Safari (recent) |
| OGG (Theora) | video/ogg | Firefox, Chrome |
The Audio Element <audio>
The <audio> element embeds audio content directly into a webpage.
Basic Syntax:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Your browser does not support the audio tag.
</audio>
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
controls | Shows playback controls | controls |
autoplay | Starts playing automatically | autoplay |
muted | Mutes the audio | muted |
loop | Replays when it ends | loop |
preload | Preloads audio data | preload="auto" |
Supported Audio Formats:
| Format | MIME Type | Browser Support |
|---|---|---|
| MP3 | audio/mpeg | All modern browsers |
| OGG (Vorbis) | audio/ogg | Firefox, Chrome |
| WAV | audio/wav | All modern browsers (uncompressed) |
The Source Element <source>
The <source> element is used within <video> and <audio> elements to specify media files in different formats.
Basic Syntax:
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
src | URL of the media file | src="video.mp4" |
type | MIME type of the media | type="video/mp4" |
media | Media query for responsive selection | media="(max-width: 768px)" |
Why Use Multiple Sources?
Browsers support different codecs. By providing multiple formats, you ensure cross-browser compatibility:
<video controls>
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<source src="video.ogv" type="video/ogg">
<!-- Fallback message -->
Your browser does not support the video tag.
</video>
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>video, audio, and source Elements</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
h3 {
color: #333;
margin-top: 20px;
}
.media-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
.media-container video,
.media-container audio {
width: 100%;
max-width: 100%;
border-radius: 8px;
background: #1e1e1e;
}
video {
background: #1e1e1e;
border-radius: 8px;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
.format-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin: 15px 0;
}
.format-card {
flex: 1;
min-width: 150px;
background: white;
padding: 15px;
border-radius: 8px;
border: 2px solid #ddd;
text-align: center;
transition: border-color 0.3s;
}
.format-card:hover {
border-color: #007bff;
}
.format-card .icon {
font-size: 2.5em;
display: block;
}
.format-card .label {
font-weight: bold;
display: block;
margin: 8px 0 5px;
}
.format-card .mime {
font-size: 0.85em;
color: #6c757d;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.reference-table tr:hover {
background: #e9ecef;
}
.fallback-message {
background: #f8d7da;
padding: 20px;
border-radius: 6px;
text-align: center;
color: #721c24;
border: 2px dashed #dc3545;
}
.thumbnail-demo {
background: #1e1e1e;
border-radius: 8px;
overflow: hidden;
min-height: 200px;
display: flex;
align-items: center;
justify-content: center;
color: #6c757d;
}
.btn-group {
margin-top: 15px;
}
button {
background: #007bff;
color: white;
padding: 10px 25px;
border: none;
border-radius: 6px;
font-size: 1em;
cursor: pointer;
transition: background 0.3s;
margin-right: 10px;
}
button:hover {
background: #0056b3;
}
button.reset {
background: #6c757d;
}
button.reset:hover {
background: #545b62;
}
</style>
</head>
<body>
<h1>video, audio, and source Elements</h1>
<!-- ====== VIDEO DEMO ====== -->
<h2>1. Video Element</h2>
<div class="media-container">
<h3>Basic Video with Controls</h3>
<video controls width="100%" poster="https://via.placeholder.com/800x400/1e1e1e/007bff?text=Video+Thumbnail">
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
<div class="fallback-message">
Your browser does not support the video tag.
</div>
</video>
<p><small>MP4 and OGG formats provided for cross-browser compatibility.</small></p>
</div>
<!-- ====== VIDEO WITH ATTRIBUTES ====== -->
<div class="media-container">
<h3>Video with Multiple Attributes</h3>
<p>This video has: <code>controls</code>, <code>muted</code>, <code>loop</code>, <code>width="100%"</code>, and <code>poster</code>.</p>
<video controls muted loop width="100%" poster="https://via.placeholder.com/800x400/28a745/ffffff?text=Loading...">
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<div class="example-box">
<h4>๐ Attributes Demonstrated:</h4>
<ul>
<li><code>controls</code> โ Play/Pause, Volume, Fullscreen buttons</li>
<li><code>muted</code> โ Audio starts muted</li>
<li><code>loop</code> โ Video replays automatically</li>
<li><code>poster</code> โ Thumbnail image displayed before playback</li>
</ul>
</div>
</div>
<!-- ====== AUDIO DEMO ====== -->
<h2>2. Audio Element</h2>
<div class="media-container">
<h3>Audio Player with Controls</h3>
<audio controls style="width: 100%;">
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
<source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
Your browser does not support the audio tag.
</audio>
<p><small>MP3 and OGG formats provided for cross-browser compatibility.</small></p>
</div>
<!-- ====== AUDIO WITH ATTRIBUTES ====== -->
<div class="media-container">
<h3>Audio with Loop and Autoplay</h3>
<p>This audio has: <code>controls</code>, <code>autoplay</code>, <code>muted</code>, and <code>loop</code>.</p>
<audio controls autoplay muted loop style="width: 100%;">
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
<source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
Your browser does not support the audio tag.
</audio>
<div class="example-box">
<h4>๐ Attributes Demonstrated:</h4>
<ul>
<li><code>controls</code> โ Play/Pause, Volume buttons</li>
<li><code>autoplay</code> โ Starts playing on load</li>
<li><code>muted</code> โ Audio starts muted (required for autoplay in most browsers)</li>
<li><code>loop</code> โ Replays automatically</li>
</ul>
<p><strong>Note:</strong> Most modern browsers require <code>muted</code> for <code>autoplay</code> to work.</p>
</div>
</div>
<!-- ====== SOURCE ELEMENT ====== -->
<h2>3. The Source Element</h2>
<div class="media-container">
<h3>Multiple Source Formats for Cross-Browser Compatibility</h3>
<video controls width="100%">
<!-- MP4 (most compatible) -->
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<!-- WebM (good compression) -->
<source src="https://www.w3schools.com/html/mov_bbb.webm" type="video/webm">
<!-- OGG (open format) -->
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
<div class="fallback-message">
Your browser does not support the video tag.
</div>
</video>
<div class="example-box">
<h4>๐ How the Browser Chooses:</h4>
<ol>
<li>Browser checks the first <code><source></code></li>
<li>If it supports the format, it uses that file</li>
<li>If not, it moves to the next <code><source></code></li>
<li>If none are supported, the fallback message is shown</li>
</ol>
</div>
</div>
<!-- ====== RESPONSIVE VIDEO ====== -->
<div class="media-container">
<h3>Responsive Video</h3>
<p>The video below adapts to the container width using <code>max-width: 100%</code> and auto height.</p>
<video controls style="max-width: 100%; height: auto; border-radius: 8px;" poster="https://via.placeholder.com/800x400/ffc107/343a40?text=Video+Ready">
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</div>
<!-- ====== FORMAT REFERENCE ====== -->
<h2>4. Supported Formats</h2>
<h3>Video Formats</h3>
<div class="format-grid">
<div class="format-card">
<span class="icon">๐ฌ</span>
<span class="label">MP4</span>
<span class="mime">video/mp4</span>
<span style="display: block; font-size: 0.85em; color: #28a745;">โ
All browsers</span>
</div>
<div class="format-card">
<span class="icon">๐ฌ</span>
<span class="label">WebM</span>
<span class="mime">video/webm</span>
<span style="display: block; font-size: 0.85em; color: #ffc107;">โ ๏ธ Chrome, Firefox, Edge</span>
</div>
<div class="format-card">
<span class="icon">๐ฌ</span>
<span class="label">OGG</span>
<span class="mime">video/ogg</span>
<span style="display: block; font-size: 0.85em; color: #ffc107;">โ ๏ธ Firefox, Chrome</span>
</div>
</div>
<h3>Audio Formats</h3>
<div class="format-grid">
<div class="format-card">
<span class="icon">๐ต</span>
<span class="label">MP3</span>
<span class="mime">audio/mpeg</span>
<span style="display: block; font-size: 0.85em; color: #28a745;">โ
All browsers</span>
</div>
<div class="format-card">
<span class="icon">๐ต</span>
<span class="label">OGG</span>
<span class="mime">audio/ogg</span>
<span style="display: block; font-size: 0.85em; color: #ffc107;">โ ๏ธ Firefox, Chrome</span>
</div>
<div class="format-card">
<span class="icon">๐ต</span>
<span class="label">WAV</span>
<span class="mime">audio/wav</span>
<span style="display: block; font-size: 0.85em; color: #28a745;">โ
All browsers (uncompressed)</span>
</div>
</div>
<!-- ====== REFERENCE TABLES ====== -->
<h2>5. Quick Reference</h2>
<h3>Video Element Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>controls</code></td>
<td>Shows playback controls</td>
<td><code><video controls></code></td>
</tr>
<tr>
<td><code>autoplay</code></td>
<td>Starts on load (needs muted)</td>
<td><code>autoplay</code></td>
</tr>
<tr>
<td><code>muted</code></td>
<td>Mutes audio</td>
<td><code>muted</code></td>
</tr>
<tr>
<td><code>loop</code></td>
<td>Replays when ended</td>
<td><code>loop</code></td>
</tr>
<tr>
<td><code>poster</code></td>
<td>Thumbnail image</td>
<td><code>poster="thumb.jpg"</code></td>
</tr>
<tr>
<td><code>width</code>/<code>height</code></td>
<td>Video dimensions</td>
<td><code>width="640" height="360"</code></td>
</tr>
</tbody>
</table>
<h3>Audio Element Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>controls</code></td>
<td>Shows playback controls</td>
<td><code><audio controls></code></td>
</tr>
<tr>
<td><code>autoplay</code></td>
<td>Starts on load (needs muted)</td>
<td><code>autoplay</code></td>
</tr>
<tr>
<td><code>muted</code></td>
<td>Mutes audio</td>
<td><code>muted</code></td>
</tr>
<tr>
<td><code>loop</code></td>
<td>Replays when ended</td>
<td><code>loop</code></td>
</tr>
</tbody>
</table>
<!-- ====== BEST PRACTICES ====== -->
<h2>6. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Always provide <strong>multiple source formats</strong> (MP4 + WebM/OGG)</li>
<li>Always include <strong>fallback text</strong> for unsupported browsers</li>
<li>Use <code>controls</code> for <strong>user-friendly playback</strong></li>
<li>Use <code>poster</code> to show a <strong>thumbnail</strong> before playback</li>
<li>Use <code>muted</code> with <code>autoplay</code> (required in most browsers)</li>
<li>Optimize video files for <strong>web performance</strong></li>
<li>Use <strong>semantic HTML</strong> and proper <strong>ARIA labels</strong></li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <code>autoplay</code> without <code>muted</code> (often blocked)</li>
<li>Don't use only one format โ some browsers won't play it</li>
<li>Don't use <strong>YouTube links</strong> in <code>src</code> (use embed instead)</li>
<li>Don't use large files without compression</li>
<li>Don't forget the <strong>fallback message</strong></li>
</ul>
</div>
<!-- ====== CODE EXAMPLES ====== -->
<h2>7. Code Examples</h2>
<div style="background: #1e1e1e; color: #d4d4d4; padding: 20px; border-radius: 8px; overflow-x: auto; font-family: 'Courier New', monospace; line-height: 1.8;">
<h3 style="color: #569cd6; margin-top: 0;">Basic Video:</h3>
<pre style="margin: 0; color: #d4d4d4;">
<span style="color: #569cd6;"><video</span> <span style="color: #9cdcfe;">controls</span> <span style="color: #9cdcfe;">width</span>=<span style="color: #ce9178;">"640"</span> <span style="color: #9cdcfe;">height</span>=<span style="color: #ce9178;">"360"</span> <span style="color: #9cdcfe;">poster</span>=<span style="color: #ce9178;">"thumbnail.jpg"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><source</span> <span style="color: #9cdcfe;">src</span>=<span style="color: #ce9178;">"video.mp4"</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"video/mp4"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><source</span> <span style="color: #9cdcfe;">src</span>=<span style="color: #ce9178;">"video.webm"</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"video/webm"</span><span style="color: #569cd6;">></span>
<span style="color: #6a9955;"><!-- Fallback message --></span>
<span style="color: #ce9178;">Your browser does not support the video tag.</span>
<span style="color: #569cd6;"></video></span>
</pre>
<h3 style="color: #569cd6;">Basic Audio:</h3>
<pre style="margin: 0; color: #d4d4d4;">
<span style="color: #569cd6;"><audio</span> <span style="color: #9cdcfe;">controls</span> <span style="color: #9cdcfe;">muted</span> <span style="color: #9cdcfe;">loop</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><source</span> <span style="color: #9cdcfe;">src</span>=<span style="color: #ce9178;">"audio.mp3"</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"audio/mpeg"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><source</span> <span style="color: #9cdcfe;">src</span>=<span style="color: #ce9178;">"audio.ogg"</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"audio/ogg"</span><span style="color: #569cd6;">></span>
<span style="color: #ce9178;">Your browser does not support the audio tag.</span>
<span style="color: #569cd6;"></audio></span>
</pre>
<h3 style="color: #569cd6;">Video with All Attributes:</h3>
<pre style="margin: 0; color: #d4d4d4;">
<span style="color: #569cd6;"><video</span>
<span style="color: #9cdcfe;">controls</span>
<span style="color: #9cdcfe;">autoplay</span>
<span style="color: #9cdcfe;">muted</span>
<span style="color: #9cdcfe;">loop</span>
<span style="color: #9cdcfe;">width</span>=<span style="color: #ce9178;">"100%"</span>
<span style="color: #9cdcfe;">poster</span>=<span style="color: #ce9178;">"thumbnail.jpg"</span>
<span style="color: #9cdcfe;">playsinline</span>
<span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><source</span> <span style="color: #9cdcfe;">src</span>=<span style="color: #ce9178;">"video.mp4"</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"video/mp4"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"><source</span> <span style="color: #9cdcfe;">src</span>=<span style="color: #ce9178;">"video.webm"</span> <span style="color: #9cdcfe;">type</span>=<span style="color: #ce9178;">"video/webm"</span><span style="color: #569cd6;">></span>
<span style="color: #ce9178;">Your browser does not support the video tag.</span>
<span style="color: #569cd6;"></video></span>
</pre>
</div>
</body>
</html>
Quick Reference
| Element | Purpose | Key Attributes |
|---|---|---|
<video> | Video playback | controls, autoplay, muted, loop, poster, width, height |
<audio> | Audio playback | controls, autoplay, muted, loop |
<source> | Media file specification | src, type, media |
Best Practices Checklist
- โ Provide multiple source formats (MP4 + WebM/OGG)
- โ Include fallback text for unsupported browsers
- โ
Use
controlsfor user playback control - โ
Use
posterfor a thumbnail image - โ
Always use
mutedwithautoplay(required in most browsers) - โ Optimize media files for web performance
- โ
Use
playsinlinefor mobile video playback - โ Test across different browsers and devices
Pro Tip: When using autoplay, always include muted. Most modern browsers block autoplay with sound. For mobile, also include playsinline to allow the video to play in the page instead of opening a full-screen player. Use <source> with multiple formats to ensure the broadest browser compatibility!
24. embed and object Elements
The <embed> and <object> elements are used to embed external resources like videos, audio files, PDFs, or even entire web pages into an HTML document. While they are older than <video> and <audio>, they still have useful applications.
Overview of Embedding Elements
| Element | Purpose | Key Features |
|---|---|---|
<embed> | Embeds external content | Simple, no fallback support |
<object> | Embeds external content | Supports fallback content |
The Embed Element <embed>
The <embed> element is a simple way to embed external resources like videos, audio, or interactive content.
Basic Syntax:
<embed src="file.mp4" width="640" height="360" title="Video Title" type="video/mp4">
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
src | URL of the resource | src="video.mp4" |
type | MIME type of the resource | type="video/mp4" |
width | Width of the embedded content | width="640" |
height | Height of the embedded content | height="360" |
title | Description of the content (accessibility) | title="My Video" |
Important Notes:
- โ Does not work with YouTube URLs โ use YouTube’s embed iframe instead
- โ Works with local video/audio files
- โ No fallback content โ if not supported, nothing is shown
- โ Can embed PDFs, images, and other media
The Object Element <object>
The <object> element is a versatile and more robust way to embed external resources. It supports fallback content if the resource cannot be loaded.
Basic Syntax:
<object type="video/mp4" data="video.mp4" width="450" height="300">
<p>Your browser does not support this content.</p>
<a href="video.mp4">Download the video</a>
</object>
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
data | URL of the resource | data="video.mp4" |
type | MIME type of the resource | type="video/mp4" |
width | Width of the embedded content | width="450" |
height | Height of the embedded content | height="300" |
name | Name of the object | name="myPlayer" |
form | Associates with a form | form="myForm" |
Important Notes:
- โ Supports fallback content โ the inner HTML is shown if the object cannot be loaded
- โ Supports PDFs, images, HTML documents, and more
- โ Can be used with Java applets and Flash (legacy)
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>embed and object Elements</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.media-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
.warning-box {
background: #fff3cd;
border: 2px solid #ffc107;
padding: 15px;
border-radius: 8px;
margin: 15px 0;
display: flex;
align-items: flex-start;
gap: 10px;
}
.warning-box .icon {
font-size: 1.5em;
}
embed, object {
max-width: 100%;
border-radius: 8px;
border: 2px solid #ddd;
background: #1e1e1e;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.reference-table tr:hover {
background: #e9ecef;
}
.comparison-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin: 15px 0;
}
.comparison-card {
flex: 1;
min-width: 250px;
background: white;
padding: 20px;
border-radius: 8px;
border: 2px solid #ddd;
}
.comparison-card h3 {
margin-top: 0;
padding-bottom: 10px;
border-bottom: 2px solid #ddd;
}
.comparison-card .check { color: #28a745; }
.comparison-card .cross { color: #dc3545; }
</style>
</head>
<body>
<h1>embed and object Elements</h1>
<!-- ====== WARNING ====== -->
<div class="warning-box">
<span class="icon">โ ๏ธ</span>
<div>
<strong>Important:</strong> The examples below use local files. If you see a blank area or error, it's because the file wasn't found.
<br>
<strong>Note:</strong> These elements <strong>do not work with YouTube links</strong>.
</div>
</div>
<!-- ====== EMBED ELEMENT ====== -->
<h2>1. The embed Element</h2>
<div class="media-container">
<h3>Embedding a Video</h3>
<embed src="https://www.w3schools.com/html/mov_bbb.mp4"
width="640"
height="360"
title="Big Buck Bunny"
type="video/mp4">
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><embed src="video.mp4" width="640" height="360" title="Big Buck Bunny" type="video/mp4"></code>
</pre>
<ul>
<li>โ
Simple to use</li>
<li>โ No fallback content</li>
<li>โ Does not support YouTube links</li>
</ul>
</div>
</div>
<!-- ====== OBJECT ELEMENT ====== -->
<h2>2. The object Element</h2>
<div class="media-container">
<h3>Object with Fallback Content</h3>
<object type="video/mp4"
data="https://www.w3schools.com/html/mov_bbb.mp4"
width="640"
height="360">
<div style="background: #f8d7da; padding: 40px; border-radius: 8px; text-align: center; border: 2px dashed #dc3545;">
<p style="font-size: 1.2em;">๐ซ Your browser does not support this content.</p>
<p><a href="https://www.w3schools.com/html/mov_bbb.mp4" download>Download the video</a></p>
</div>
</object>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><object type="video/mp4" data="video.mp4" width="640" height="360">
<p>Your browser does not support this content.</p>
<a href="video.mp4">Download the video</a>
</object></code>
</pre>
<ul>
<li>โ
Supports fallback content</li>
<li>โ
More versatile</li>
<li>โ Does not support YouTube links</li>
</ul>
</div>
</div>
<!-- ====== EMBEDDING PDF ====== -->
<div class="media-container">
<h3>Embedding a PDF</h3>
<object type="application/pdf"
data="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
width="100%"
height="500">
<div style="background: #f8d7da; padding: 40px; border-radius: 8px; text-align: center; border: 2px dashed #dc3545;">
<p style="font-size: 1.2em;">๐ Your browser cannot display this PDF.</p>
<p><a href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" target="_blank">Open PDF in new tab</a></p>
</div>
</object>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><object type="application/pdf" data="document.pdf" width="100%" height="500">
<p>Your browser cannot display this PDF.</p>
<a href="document.pdf">Open PDF</a>
</object></code>
</pre>
</div>
</div>
<!-- ====== EMBEDDING IMAGE ====== -->
<div class="media-container">
<h3>Embedding an Image</h3>
<object type="image/png"
data="https://via.placeholder.com/800x300/007bff/ffffff?text=Embedded+Image"
width="100%"
height="300">
<p>Image could not be loaded.</p>
</object>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><object type="image/png" data="image.png" width="100%" height="300">
<p>Image could not be loaded.</p>
</object></code>
</pre>
</div>
</div>
<!-- ====== COMPARISON ====== -->
<h2>3. Comparison: embed vs object</h2>
<div class="comparison-grid">
<div class="comparison-card">
<h3>๐ฒ embed</h3>
<ul>
<li><span class="check">โ
</span> Simple syntax</li>
<li><span class="cross">โ</span> No fallback content</li>
<li><span class="cross">โ</span> Limited attributes</li>
<li><span class="cross">โ</span> No YouTube support</li>
<li><span class="check">โ
</span> Fast loading</li>
</ul>
</div>
<div class="comparison-card">
<h3>๐ฆ object</h3>
<ul>
<li><span class="check">โ
</span> Supports fallback content</li>
<li><span class="check">โ
</span> More attributes</li>
<li><span class="check">โ
</span> More versatile</li>
<li><span class="cross">โ</span> No YouTube support</li>
<li><span class="check">โ
</span> Better accessibility</li>
</ul>
</div>
</div>
<!-- ====== REFERENCE TABLES ====== -->
<h2>4. Quick Reference</h2>
<h3>embed Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Purpose</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>src</code></td>
<td>URL of the resource</td>
<td><code>src="video.mp4"</code></td>
</tr>
<tr>
<td><code>type</code></td>
<td>MIME type</td>
<td><code>type="video/mp4"</code></td>
</tr>
<tr>
<td><code>width</code>/<code>height</code></td>
<td>Dimensions</td>
<td><code>width="640" height="360"</code></td>
</tr>
</tbody>
</table>
<h3>object Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Purpose</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>data</code></td>
<td>URL of the resource</td>
<td><code>data="video.mp4"</code></td>
</tr>
<tr>
<td><code>type</code></td>
<td>MIME type</td>
<td><code>type="video/mp4"</code></td>
</tr>
<tr>
<td><code>width</code>/<code>height</code></td>
<td>Dimensions</td>
<td><code>width="640" height="360"</code></td>
</tr>
<tr>
<td><code>name</code></td>
<td>Name for scripting</td>
<td><code>name="myPlayer"</code></td>
</tr>
<tr>
<td><code>form</code></td>
<td>Associates with a form</td>
<td><code>form="myForm"</code></td>
</tr>
</tbody>
</table>
<h3>Common MIME Types</h3>
<table class="reference-table">
<thead>
<tr>
<th>Content Type</th>
<th>MIME Type</th>
<th>Use Case</th>
</tr>
</thead>
<tbody>
<tr>
<td>Video</td>
<td><code>video/mp4</code></td>
<td>MP4 videos</td>
</tr>
<tr>
<td>Video</td>
<td><code>video/webm</code></td>
<td>WebM videos</td>
</tr>
<tr>
<td>Audio</td>
<td><code>audio/mpeg</code></td>
<td>MP3 audio</td>
</tr>
<tr>
<td>PDF</td>
<td><code>application/pdf</code></td>
<td>PDF documents</td>
</tr>
<tr>
<td>Image</td>
<td><code>image/png</code></td>
<td>PNG images</td>
</tr>
<tr>
<td>Image</td>
<td><code>image/jpeg</code></td>
<td>JPEG images</td>
</tr>
<tr>
<td>HTML</td>
<td><code>text/html</code></td>
<td>HTML pages</td>
</tr>
</tbody>
</table>
<!-- ====== BEST PRACTICES ====== -->
<h2>5. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Use <code><object></code> instead of <code><embed></code> when you need <strong>fallback content</strong></li>
<li>Include a <strong>download link</strong> in the fallback content</li>
<li>Use the <strong>correct MIME type</strong> for your content</li>
<li>Set appropriate <code>width</code> and <code>height</code> for your content</li>
<li>Use <code>title</code> attribute for <strong>accessibility</strong></li>
<li>Consider using <code><video></code> or <code><audio></code> for modern media</li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <code><embed></code> or <code><object></code> with <strong>YouTube URLs</strong> (they won't work)</li>
<li>Don't forget to include <strong>fallback content</strong> with <code><object></code></li>
<li>Don't use <code><embed></code> without a <code>type</code> attribute</li>
<li>Don't rely solely on these for video โ use <code><video></code> when possible</li>
<li>Don't use <code><object></code> for <strong>modern video</strong> โ use <code><video></code> instead</li>
</ul>
</div>
</body>
</html>
Quick Reference
| Element | Purpose | Fallback | YouTube Support |
|---|---|---|---|
<embed> | Embed external content | โ No | โ No |
<object> | Embed external content with fallback | โ Yes | โ No |
When to Use What
| Content Type | Recommended Element |
|---|---|
| Modern video | <video> with <source> |
| Modern audio | <audio> with <source> |
| PDF documents | <object> or <iframe> |
| Images | <img> or <picture> |
| Legacy content | <object> |
| Simple embedded media | <embed> |
Pro Tip: For modern web development, prefer <video>, <audio>, and <iframe> over <embed> and <object>. However, <object> is still valuable for embedding PDFs and other documents where you need fallback content. Always test your embedded content across different browsers!
25. SVG: Scalable Vector Graphics
SVG (Scalable Vector Graphics) is a powerful way to create resolution-independent graphics directly in HTML. Unlike raster images (JPEG, PNG), SVGs maintain quality at any size and can be styled, animated, and manipulated with CSS and JavaScript.
What is SVG?
SVG is an XML-based markup language for describing two-dimensional vector graphics. It’s perfect for:
- Logos and icons
- Illustrations and diagrams
- Charts and data visualizations
- Interactive graphics (hover effects, animations)
Key Benefits:
| Benefit | Description |
|---|---|
| Scalability | No quality loss at any size |
| Small file size | For simple graphics |
| Styling | Style with CSS like HTML elements |
| Interactivity | Support for onclick, onmouseover, etc. |
| Accessibility | Can include text and ARIA labels |
| JavaScript | Can be manipulated with JS |
Adding SVG to HTML
There are three ways to include SVG in your HTML:
1. Inline SVG (Recommended)
<svg width="200" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="yellow" stroke="green" stroke-width="4"/>
</svg>
2. Using <img> Tag
<img src="image.svg" alt="Description of SVG image">
3. Using <object> Tag
<object type="image/svg+xml" data="image.svg"></object>
Basic SVG Attributes
| Attribute | Purpose | Example |
|---|---|---|
width | Width of the SVG canvas | width="200" |
height | Height of the SVG canvas | height="200" |
viewBox | Defines the coordinate system | viewBox="0 0 100 100" |
Understanding viewBox:
viewBox = "min-x min-y width height"
- The
viewBoxdefines the internal coordinate system - It’s like setting up your own grid
viewBox="0 0 100 100"creates a 100ร100 grid regardless of canvas size
Common SVG Shapes
| Element | Shape | Key Attributes |
|---|---|---|
<rect> | Rectangle | x, y, width, height, rx, ry |
<circle> | Circle | cx, cy, r |
<ellipse> | Ellipse | cx, cy, rx, ry |
<line> | Straight line | x1, y1, x2, y2 |
<polyline> | Connected line segments | points |
<polygon> | Closed shape | points |
<path> | Complex paths | d (commands) |
Common Styling Attributes
| Attribute | Purpose | Example |
|---|---|---|
fill | Fill color of the shape | fill="blue" or fill="#007bff" |
stroke | Border/outline color | stroke="green" |
stroke-width | Width of the border | stroke-width="4" |
opacity | Transparency (0โ1) | opacity="0.5" |
fill-opacity | Fill transparency | fill-opacity="0.8" |
The Circle Element <circle>
The <circle> element creates circular shapes.
Basic Syntax:
<circle cx="50" cy="50" r="40" fill="yellow" stroke="green" stroke-width="4"/>
Browser Display:
A yellow circle with a green border.
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
cx | X-coordinate of the center | cx="50" |
cy | Y-coordinate of the center | cy="50" |
r | Radius of the circle | r="40" |
The Rectangle Element <rect>
The <rect> element creates rectangles and squares.
Basic Syntax:
<rect width="150" height="75" x="25" y="12.5" fill="#007bff" stroke="#0056b3" stroke-width="2"/>
Browser Display:
A blue rectangle with a dark blue border.
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
x | X-coordinate of the top-left corner | x="25" |
y | Y-coordinate of the top-left corner | y="12.5" |
width | Width of the rectangle | width="150" |
height | Height of the rectangle | height="75" |
rx | Corner radius (rounded corners) | rx="10" |
ry | Corner radius (vertical) | ry="10" |
The Polygon Element <polygon>
The <polygon> element creates closed shapes with three or more sides.
Basic Syntax:
<polygon points="100,10 40,180 190,60 10,60 160,180" fill="purple" stroke="green" stroke-width="2"/>
Browser Display:
A purple star shape with a green border.
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
points | List of x,y coordinate pairs | points="10,10 100,10 100,100" |
The points attribute is a space or comma-separated list of coordinates:
points="x1,y1 x2,y2 x3,y3 ..."
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Elements: Circle, Polygon, Rect</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
h3 {
color: #333;
margin-top: 20px;
}
.svg-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
display: flex;
flex-wrap: wrap;
gap: 30px;
align-items: center;
}
.svg-container svg {
background: #f8f9fa;
border-radius: 8px;
border: 1px solid #ddd;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
flex: 1;
min-width: 250px;
}
.grid-3 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin: 15px 0;
}
.grid-3 .shape-card {
background: white;
padding: 15px;
border-radius: 8px;
border: 2px solid #ddd;
text-align: center;
}
.shape-card:hover {
border-color: #007bff;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.95em;
line-height: 1.8;
margin: 10px 0;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.reference-table tr:hover {
background: #e9ecef;
}
.comparison-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin: 15px 0;
}
.comparison-card {
flex: 1;
min-width: 200px;
background: white;
padding: 20px;
border-radius: 8px;
border: 2px solid #ddd;
}
.comparison-card h3 {
margin-top: 0;
padding-bottom: 10px;
border-bottom: 2px solid #ddd;
}
.hover-demo svg {
transition: transform 0.3s;
}
.hover-demo svg:hover {
transform: scale(1.05);
}
.interactive-demo .shape {
transition: all 0.3s;
}
.interactive-demo .shape:hover {
fill: #ff6b6b;
stroke: #c92a2a;
stroke-width: 4;
cursor: pointer;
}
</style>
</head>
<body>
<h1>SVG: Circle, Polygon, and Rect</h1>
<!-- ====== SECTION 1: BASIC SVG ====== -->
<h2>1. Basic SVG with ViewBox</h2>
<div class="svg-container">
<div>
<h3>Without ViewBox</h3>
<svg width="200" height="100">
<circle cx="50" cy="50" r="40" fill="yellow" stroke="green" stroke-width="4"/>
</svg>
<p><small>200ร100 canvas, circle at (50,50)</small></p>
</div>
<div>
<h3>With ViewBox</h3>
<svg width="200" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="yellow" stroke="green" stroke-width="4"/>
</svg>
<p><small>200ร100 canvas, viewBox="0 0 100 100" โ circle scales</small></p>
</div>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><svg width="200" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="yellow" stroke="green" stroke-width="4"/>
</svg></code>
</pre>
</div>
</div>
<!-- ====== SECTION 2: CIRCLE ====== -->
<h2>2. Circle Element</h2>
<div class="svg-container">
<svg width="200" height="200" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="80" fill="#ffc107" stroke="#007bff" stroke-width="5"/>
</svg>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><circle cx="100" cy="100" r="80" fill="#ffc107" stroke="#007bff" stroke-width="5"/></code>
</pre>
<ul>
<li><code>cx="100"</code> โ Center X</li>
<li><code>cy="100"</code> โ Center Y</li>
<li><code>r="80"</code> โ Radius</li>
<li><code>fill="#ffc107"</code> โ Yellow fill</li>
<li><code>stroke="#007bff"</code> โ Blue border</li>
<li><code>stroke-width="5"</code> โ Border thickness</li>
</ul>
</div>
</div>
<!-- ====== SECTION 3: RECTANGLE ====== -->
<h2>3. Rectangle Element</h2>
<div class="svg-container">
<svg width="200" height="150" viewBox="0 0 200 150">
<!-- Standard rectangle -->
<rect x="25" y="12.5" width="150" height="75" fill="#007bff" stroke="#0056b3" stroke-width="3"/>
<!-- Rounded rectangle -->
<rect x="25" y="12.5" width="150" height="75" fill="none" stroke="#28a745" stroke-width="3" rx="15" ry="15"/>
</svg>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><rect x="25" y="12.5" width="150" height="75" fill="#007bff" stroke="#0056b3" stroke-width="3"/>
<rect x="25" y="12.5" width="150" height="75" fill="none" stroke="#28a745" stroke-width="3" rx="15" ry="15"/></code>
</pre>
<ul>
<li><code>x="25"</code> โ X coordinate</li>
<li><code>y="12.5"</code> โ Y coordinate</li>
<li><code>width="150"</code> โ Width</li>
<li><code>height="75"</code> โ Height</li>
<li><code>rx="15"</code>, <code>ry="15"</code> โ Rounded corners</li>
</ul>
</div>
</div>
<!-- ====== SECTION 4: POLYGON ====== -->
<h2>4. Polygon Element</h2>
<div class="svg-container">
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- Triangle -->
<polygon points="100,10 190,180 10,180" fill="#28a745" stroke="#1e7e34" stroke-width="3"/>
<!-- Star -->
<polygon points="100,60 120,150 50,95 150,95 80,150" fill="none" stroke="#dc3545" stroke-width="3"/>
</svg>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><!-- Triangle -->
<polygon points="100,10 190,180 10,180" fill="#28a745" stroke="#1e7e34" stroke-width="3"/>
<!-- Star -->
<polygon points="100,60 120,150 50,95 150,95 80,150" fill="none" stroke="#dc3545" stroke-width="3"/></code>
</pre>
<ul>
<li><code>points="x1,y1 x2,y2 x3,y3 ..."</code></li>
<li>Triangle: 3 points (100,10), (190,180), (10,180)</li>
<li>Star: 5 points forming a star shape</li>
</ul>
</div>
</div>
<!-- ====== SECTION 5: STYLING WITH CSS ====== -->
<h2>5. Styling SVG with CSS</h2>
<div class="svg-container" style="flex-direction: column;">
<div style="display: flex; flex-wrap: wrap; gap: 30px; width: 100%;">
<div style="flex: 1; min-width: 250px;">
<h3>With CSS Class</h3>
<svg width="200" height="200" viewBox="0 0 200 200">
<style>
.star { fill: purple; stroke: green; stroke-width: 2; }
.star:hover { fill: orange; cursor: pointer; }
</style>
<polygon class="star" points="100,10 40,180 190,60 10,60 160,180"/>
</svg>
<p><small>Hover over the star โ it changes color!</small></p>
</div>
<div style="flex: 1; min-width: 250px;">
<h3>With Hover Effect</h3>
<svg width="200" height="200" viewBox="0 0 200 200">
<rect x="25" y="25" width="150" height="150" rx="20" fill="#007bff" stroke="#0056b3" stroke-width="3"
style="transition: all 0.3s;"
onmouseover="this.setAttribute('fill', '#28a745')"
onmouseout="this.setAttribute('fill', '#007bff')"/>
</svg>
<p><small>Hover over the rectangle โ it changes color!</small></p>
</div>
</div>
<div class="example-box" style="width: 100%;">
<h4>๐ CSS Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><style>
.star { fill: purple; stroke: green; stroke-width: 2; }
.star:hover { fill: orange; }
</style>
<polygon class="star" points="100,10 40,180 190,60 10,60 160,180"/></code>
</pre>
</div>
</div>
<!-- ====== SECTION 6: MORE SHAPES ====== -->
<h2>6. More SVG Shapes</h2>
<div class="svg-container" style="flex-direction: column; gap: 20px;">
<div class="grid-3">
<div class="shape-card">
<h4>Circle</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<circle cx="60" cy="60" r="50" fill="#ff6b6b" stroke="#c92a2a" stroke-width="3"/>
</svg>
</div>
<div class="shape-card">
<h4>Ellipse</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<ellipse cx="60" cy="60" rx="50" ry="30" fill="#4ecdc4" stroke="#0ca678" stroke-width="3"/>
</svg>
</div>
<div class="shape-card">
<h4>Rectangle</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<rect x="20" y="30" width="80" height="60" fill="#ffd93d" stroke="#fab005" stroke-width="3"/>
</svg>
</div>
<div class="shape-card">
<h4>Rounded Rectangle</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<rect x="20" y="30" width="80" height="60" rx="15" ry="15" fill="#6c5ce7" stroke="#4a2a9e" stroke-width="3"/>
</svg>
</div>
<div class="shape-card">
<h4>Triangle</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<polygon points="60,10 110,100 10,100" fill="#00b894" stroke="#005b4f" stroke-width="3"/>
</svg>
</div>
<div class="shape-card">
<h4>Star</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<polygon points="60,10 70,50 110,50 80,75 90,110 60,90 30,110 40,75 10,50 50,50" fill="#e17055" stroke="#d63031" stroke-width="2"/>
</svg>
</div>
</div>
</div>
<!-- ====== SECTION 7: INTERACTIVE SVG ====== -->
<h2>7. Interactive SVG</h2>
<div class="svg-container" style="flex-direction: column;">
<div style="display: flex; flex-wrap: wrap; gap: 30px; width: 100%;">
<div style="flex: 1; min-width: 250px;">
<h3>Click Interaction</h3>
<svg width="200" height="200" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="70" fill="#ffc107" stroke="#007bff" stroke-width="3"
style="cursor: pointer; transition: all 0.3s;"
onclick="alert('You clicked the circle!')"
onmouseover="this.setAttribute('fill', '#ff6b6b')"
onmouseout="this.setAttribute('fill', '#ffc107')"/>
</svg>
<p><small>Hover โ changes color<br>Click โ shows alert</small></p>
</div>
<div style="flex: 1; min-width: 250px;">
<h3>Transform Animation</h3>
<svg width="200" height="200" viewBox="0 0 200 200">
<rect x="50" y="50" width="100" height="100" rx="10" fill="#28a745" stroke="#1e7e34" stroke-width="3"
style="cursor: pointer; transition: all 0.5s;"
onmouseover="this.setAttribute('transform', 'rotate(45, 100, 100)')"
onmouseout="this.setAttribute('transform', 'rotate(0, 100, 100)')"/>
</svg>
<p><small>Hover โ rotates 45 degrees</small></p>
</div>
</div>
</div>
<!-- ====== SECTION 8: REFERENCE TABLES ====== -->
<h2>8. Quick Reference</h2>
<h3>SVG Shape Elements</h3>
<table class="reference-table">
<thead>
<tr>
<th>Element</th>
<th>Purpose</th>
<th>Key Attributes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><circle></code></td>
<td>Circle</td>
<td><code>cx</code>, <code>cy</code>, <code>r</code></td>
</tr>
<tr>
<td><code><rect></code></td>
<td>Rectangle</td>
<td><code>x</code>, <code>y</code>, <code>width</code>, <code>height</code>, <code>rx</code>, <code>ry</code></td>
</tr>
<tr>
<td><code><polygon></code></td>
<td>Polygon</td>
<td><code>points</code></td>
</tr>
<tr>
<td><code><ellipse></code></td>
<td>Ellipse</td>
<td><code>cx</code>, <code>cy</code>, <code>rx</code>, <code>ry</code></td>
</tr>
<tr>
<td><code><line></code></td>
<td>Line</td>
<td><code>x1</code>, <code>y1</code>, <code>x2</code>, <code>y2</code></td>
</tr>
<tr>
<td><code><polyline></code></td>
<td>Connected lines</td>
<td><code>points</code></td>
</tr>
<tr>
<td><code><path></code></td>
<td>Complex path</td>
<td><code>d</code></td>
</tr>
</tbody>
</table>
<h3>Common Styling Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Purpose</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>fill</code></td>
<td>Interior color</td>
<td><code>fill="blue"</code></td>
</tr>
<tr>
<td><code>stroke</code></td>
<td>Border color</td>
<td><code>stroke="green"</code></td>
</tr>
<tr>
<td><code>stroke-width</code></td>
<td>Border thickness</td>
<td><code>stroke-width="4"</code></td>
</tr>
<tr>
<td><code>opacity</code></td>
<td>Transparency</td>
<td><code>opacity="0.5"</code></td>
</tr>
<tr>
<td><code>fill-opacity</code></td>
<td>Fill transparency</td>
<td><code>fill-opacity="0.8"</code></td>
</tr>
<tr>
<td><code>stroke-opacity</code></td>
<td>Stroke transparency</td>
<td><code>stroke-opacity="0.7"</code></td>
</tr>
</tbody>
</table>
<!-- ====== SECTION 9: BEST PRACTICES ====== -->
<h2>9. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Use <strong>inline SVG</strong> for small, reusable graphics</li>
<li>Use <code>viewBox</code> for <strong>scalability</strong></li>
<li>Use <strong>CSS classes</strong> for consistent styling</li>
<li>Add <code>aria-label</code> or <code>title</code> for <strong>accessibility</strong></li>
<li>Use <strong>semantic shapes</strong> instead of paths when possible</li>
<li>Optimize SVG files by <strong>minimizing unnecessary code</strong></li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <strong>PNG/JPEG</strong> for graphics that should be scalable</li>
<li>Don't forget to set <code>viewBox</code> for <strong>proper scaling</strong></li>
<li>Don't use overly complex paths when simpler shapes work</li>
<li>Don't use SVG for <strong>complex photographs</strong> (use JPEG instead)</li>
<li>Don't use too many <strong>nested elements</strong> without optimization</li>
</ul>
</div>
</body>
</html>
Quick Reference
| Element | Purpose | Key Attributes |
|---|---|---|
<svg> | SVG container | width, height, viewBox |
<circle> | Circle | cx, cy, r |
<rect> | Rectangle | x, y, width, height, rx, ry |
<polygon> | Polygon | points |
<ellipse> | Ellipse | cx, cy, rx, ry |
<line> | Line | x1, y1, x2, y2 |
When to Use SVG vs Other Formats
| Format | Best For | Why |
|---|---|---|
| SVG | Logos, icons, illustrations | Scalable, small size, styleable |
| PNG | Images with transparency | Raster, good for web |
| JPEG | Photographs | Good compression |
| WebP | Web images | Modern, better compression |
Pro Tip: Use inline SVG for icons and simple graphics. It’s more performant than loading external files and allows for easy styling and interactivity. Remember to add viewBox to your SVG elements so they scale properly in different contexts!
26. ellipse, line, path, and polyline
SVG provides several elements for creating shapes and lines. This chapter covers four essential SVG elements: <ellipse>, <line>, <path>, and <polyline>. Each serves a unique purpose in vector graphics.
Overview of SVG Shape Elements
| Element | Purpose | Key Attributes |
|---|---|---|
<ellipse> | Elliptical/circular shapes | cx, cy, rx, ry |
<line> | Straight line | x1, y1, x2, y2 |
<polyline> | Connected straight lines | points |
<path> | Complex shapes and curves | d (commands) |
The Ellipse Element <ellipse>
The <ellipse> element creates elliptical shapes, including circles.
Basic Syntax:
<ellipse cx="150" cy="100" rx="80" ry="50" fill="yellow" stroke="blue" stroke-width="3"/>
Browser Display:
A yellow ellipse with a blue border.
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
cx | X-coordinate of the center | cx="150" |
cy | Y-coordinate of the center | cy="100" |
rx | Radius on the X-axis (horizontal) | rx="80" |
ry | Radius on the Y-axis (vertical) | ry="50" |
Important Note:
- If
rxequalsry, the shape becomes a circle - If
rxandrydiffer, it’s an ellipse
The Line Element <line>
The <line> element creates a simple straight line between two points.
Basic Syntax:
<line x1="20" y1="20" x2="180" y2="180" stroke="blue" stroke-width="2"/>
Browser Display:
A blue diagonal line.
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
x1 | X-coordinate of the start point | x1="20" |
y1 | Y-coordinate of the start point | y1="20" |
x2 | X-coordinate of the end point | x2="180" |
y2 | Y-coordinate of the end point | y2="180" |
The Polyline Element <polyline>
The <polyline> element creates a series of connected straight lines, forming an open or closed shape.
Basic Syntax:
<polyline points="0,100 50,25 50,75 100,0" fill="red" stroke="blue" stroke-width="2"/>
Browser Display:
A zigzag line in red and blue.
Attributes:
| Attribute | Purpose | Example |
|---|---|---|
points | List of x,y coordinate pairs | points="x1,y1 x2,y2 x3,y3 ..." |
fill | Interior color (if closed) | fill="red" |
stroke | Line color | stroke="blue" |
stroke-width | Line thickness | stroke-width="2" |
Polyline vs Polygon:
| Feature | Polyline | Polygon |
|---|---|---|
| Shape | Open or closed | Always closed |
| Fill | Only fills if closed | Always fills |
| Use case | Paths, zigzags, open shapes | Triangles, stars, closed shapes |
The Path Element <path>
The <path> element is the most powerful SVG shape element. It can create any shape using a series of commands.
Basic Syntax:
<path d="M 10 10 L 90 90" stroke="blue" stroke-width="2"/>
Browser Display:
A diagonal line from (10,10) to (90,90).
Path Commands:
| Command | Meaning | Example | Description |
|---|---|---|---|
M | Move to | M 10 10 | Moves cursor to (10,10) |
L | Line to | L 90 90 | Draws line to (90,90) |
H | Horizontal line | H 100 | Draws horizontal line to X=100 |
V | Vertical line | V 100 | Draws vertical line to Y=100 |
C | Cubic Bezier | C x1 y1, x2 y2, x y | Draws curve with two control points |
S | Smooth Cubic | S x2 y2, x y | Smooth curve with one control point |
Q | Quadratic Bezier | Q x1 y1, x y | Draws curve with one control point |
T | Smooth Quadratic | T x y | Smooth quadratic curve |
A | Arc | A rx ry x-axis-rotation large-arc sweep x y | Draws an arc |
Z | Close path | Z | Closes the path |
Path Example (House Shape):
<path d="M 100 20 L 20 100 L 100 180 L 180 100 Z" fill="yellow" stroke="blue" stroke-width="3"/>
This draws a diamond/house shape.
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG: ellipse, line, path, polyline</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
h3 {
color: #333;
margin-top: 20px;
}
.svg-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
display: flex;
flex-wrap: wrap;
gap: 30px;
align-items: center;
}
.svg-container svg {
background: #fafafa;
border-radius: 8px;
border: 1px solid #e9ecef;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
flex: 1;
min-width: 250px;
}
.grid-3 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin: 15px 0;
}
.grid-3 .shape-card {
background: white;
padding: 15px;
border-radius: 8px;
border: 2px solid #ddd;
text-align: center;
}
.shape-card:hover {
border-color: #007bff;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.95em;
line-height: 1.8;
margin: 10px 0;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.reference-table tr:hover {
background: #e9ecef;
}
.command-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 15px;
margin: 15px 0;
}
.command-card {
background: white;
padding: 15px;
border-radius: 8px;
border: 2px solid #ddd;
}
.command-card .cmd {
font-family: 'Courier New', monospace;
font-weight: bold;
color: #007bff;
font-size: 1.2em;
}
.command-card .desc {
color: #6c757d;
margin-top: 5px;
}
.comparison-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin: 15px 0;
}
.comparison-card {
flex: 1;
min-width: 200px;
background: white;
padding: 20px;
border-radius: 8px;
border: 2px solid #ddd;
}
.comparison-card h3 {
margin-top: 0;
padding-bottom: 10px;
border-bottom: 2px solid #ddd;
}
</style>
</head>
<body>
<h1>SVG: ellipse, line, path, polyline</h1>
<!-- ====== SECTION 1: ELLIPSE ====== -->
<h2>1. Ellipse Element</h2>
<div class="svg-container">
<svg width="300" height="200" viewBox="0 0 300 200">
<!-- Standard ellipse -->
<ellipse cx="150" cy="100" rx="80" ry="50" fill="#ffc107" stroke="#007bff" stroke-width="3"/>
<!-- Circle (rx = ry) -->
<ellipse cx="150" cy="100" rx="30" ry="30" fill="none" stroke="#dc3545" stroke-width="2"/>
</svg>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><ellipse cx="150" cy="100" rx="80" ry="50"
fill="#ffc107" stroke="#007bff" stroke-width="3"/>
<ellipse cx="150" cy="100" rx="30" ry="30"
fill="none" stroke="#dc3545" stroke-width="2"/></code>
</pre>
<ul>
<li><code>cx="150"</code> โ Center X</li>
<li><code>cy="100"</code> โ Center Y</li>
<li><code>rx="80"</code> โ Horizontal radius</li>
<li><code>ry="50"</code> โ Vertical radius</li>
<li>If <code>rx = ry</code>, it's a circle</li>
</ul>
</div>
</div>
<!-- ====== SECTION 2: LINE ====== -->
<h2>2. Line Element</h2>
<div class="svg-container">
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- Diagonal line -->
<line x1="20" y1="20" x2="180" y2="180" stroke="#007bff" stroke-width="4"/>
<!-- Horizontal line -->
<line x1="20" y1="100" x2="180" y2="100" stroke="#28a745" stroke-width="3" stroke-dasharray="10,5"/>
<!-- Vertical line -->
<line x1="100" y1="20" x2="100" y2="180" stroke="#dc3545" stroke-width="3" stroke-dasharray="5,5"/>
</svg>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><!-- Diagonal line -->
<line x1="20" y1="20" x2="180" y2="180" stroke="#007bff" stroke-width="4"/>
<!-- Dashed horizontal line -->
<line x1="20" y1="100" x2="180" y2="100" stroke="#28a745" stroke-width="3" stroke-dasharray="10,5"/>
<!-- Dashed vertical line -->
<line x1="100" y1="20" x2="100" y2="180" stroke="#dc3545" stroke-width="3" stroke-dasharray="5,5"/></code>
</pre>
<ul>
<li><code>x1,y1</code> โ Start point</li>
<li><code>x2,y2</code> โ End point</li>
<li><code>stroke-dasharray</code> โ Creates dashed lines</li>
</ul>
</div>
</div>
<!-- ====== SECTION 3: POLYLINE ====== -->
<h2>3. Polyline Element</h2>
<div class="svg-container">
<svg width="200" height="150" viewBox="0 0 200 150">
<!-- Zigzag polyline -->
<polyline points="0,100 50,25 50,75 100,0 100,50 150,25 150,75 200,50"
fill="none" stroke="#007bff" stroke-width="3"/>
<!-- Closed polyline with fill -->
<polyline points="0,120 50,50 100,90 150,50 200,100 100,140"
fill="#ffc107" stroke="#dc3545" stroke-width="2"/>
</svg>
<div class="example-box">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><!-- Open zigzag -->
<polyline points="0,100 50,25 50,75 100,0 100,50 150,25 150,75 200,50"
fill="none" stroke="#007bff" stroke-width="3"/>
<!-- Closed polyline with fill -->
<polyline points="0,120 50,50 100,90 150,50 200,100 100,140"
fill="#ffc107" stroke="#dc3545" stroke-width="2"/></code>
</pre>
<ul>
<li><code>points</code> โ List of x,y coordinates</li>
<li><code>fill</code> โ Fills the shape if closed</li>
<li><code>fill="none"</code> โ Makes it an open path</li>
</ul>
</div>
</div>
<!-- ====== SECTION 4: PATH ====== -->
<h2>4. Path Element</h2>
<div class="svg-container" style="flex-direction: column;">
<div style="display: flex; flex-wrap: wrap; gap: 30px; width: 100%;">
<!-- Simple Path -->
<div style="flex: 1; min-width: 250px;">
<h3>Simple Path</h3>
<svg width="200" height="200" viewBox="0 0 200 200">
<path d="M 10 10 L 90 90" stroke="#007bff" stroke-width="4"/>
<path d="M 10 90 L 90 10" stroke="#dc3545" stroke-width="4"/>
</svg>
<p><small>Two diagonal lines using <code>M</code> and <code>L</code></small></p>
</div>
<!-- House Shape -->
<div style="flex: 1; min-width: 250px;">
<h3>House Shape</h3>
<svg width="200" height="200" viewBox="0 0 200 200">
<path d="M 100 20 L 20 100 L 100 180 L 180 100 Z"
fill="#ffc107" stroke="#007bff" stroke-width="3"/>
</svg>
<p><small><code>M 100 20</code> โ <code>L 20 100</code> โ <code>L 100 180</code> โ <code>L 180 100</code> โ <code>Z</code> (close)</small></p>
</div>
<!-- Heart Shape -->
<div style="flex: 1; min-width: 250px;">
<h3>Heart Shape</h3>
<svg width="200" height="200" viewBox="0 0 200 200">
<path d="M 100 180 C 40 120, 0 80, 20 40 C 40 0, 80 20, 100 60 C 120 20, 160 0, 180 40 C 200 80, 160 120, 100 180 Z"
fill="#dc3545" stroke="#c92a2a" stroke-width="2"/>
</svg>
<p><small>Bezier curves (<code>C</code>) for smooth shapes</small></p>
</div>
</div>
<div class="example-box" style="width: 100%;">
<h4>๐ Code:</h4>
<pre style="background: #f4f4f4; color: #333; padding: 10px; border-radius: 4px; overflow-x: auto;">
<code><!-- House shape -->
<path d="M 100 20 L 20 100 L 100 180 L 180 100 Z"
fill="#ffc107" stroke="#007bff" stroke-width="3"/>
<!-- Heart shape -->
<path d="M 100 180 C 40 120, 0 80, 20 40 C 40 0, 80 20, 100 60 C 120 20, 160 0, 180 40 C 200 80, 160 120, 100 180 Z"
fill="#dc3545" stroke="#c92a2a" stroke-width="2"/></code>
</pre>
</div>
</div>
<!-- ====== SECTION 5: PATH COMMANDS ====== -->
<h2>5. Path Commands Reference</h2>
<div class="command-grid">
<div class="command-card">
<span class="cmd">M x y</span>
<div class="desc">Move to โ sets starting point</div>
</div>
<div class="command-card">
<span class="cmd">L x y</span>
<div class="desc">Line to โ draws a straight line</div>
</div>
<div class="command-card">
<span class="cmd">H x</span>
<div class="desc">Horizontal line to โ draws a line horizontally</div>
</div>
<div class="command-card">
<span class="cmd">V y</span>
<div class="desc">Vertical line to โ draws a line vertically</div>
</div>
<div class="command-card">
<span class="cmd">C x1 y1, x2 y2, x y</span>
<div class="desc">Cubic Bezier curve โ smooth curve with two control points</div>
</div>
<div class="command-card">
<span class="cmd">S x2 y2, x y</span>
<div class="desc">Smooth cubic โ continues a curve smoothly</div>
</div>
<div class="command-card">
<span class="cmd">Q x1 y1, x y</span>
<div class="desc">Quadratic Bezier โ simple curve with one control point</div>
</div>
<div class="command-card">
<span class="cmd">T x y</span>
<div class="desc">Smooth quadratic โ continues a quadratic curve smoothly</div>
</div>
<div class="command-card">
<span class="cmd">A rx ry rot large sweep x y</span>
<div class="desc">Arc โ draws an elliptical arc</div>
</div>
<div class="command-card">
<span class="cmd">Z</span>
<div class="desc">Close path โ returns to the starting point</div>
</div>
</div>
<!-- ====== SECTION 6: COMPARISON ====== -->
<h2>6. Comparison: polyline vs polygon vs path</h2>
<div class="comparison-grid">
<div class="comparison-card">
<h3>๐ Polyline</h3>
<svg width="150" height="100" viewBox="0 0 150 100">
<polyline points="10,90 50,10 90,50 130,10" fill="none" stroke="#007bff" stroke-width="3"/>
</svg>
<ul>
<li>โ
Open or closed shape</li>
<li>โ
Simple connected lines</li>
<li>โ No curves</li>
<li>โ Limited control</li>
</ul>
</div>
<div class="comparison-card">
<h3>๐บ Polygon</h3>
<svg width="150" height="100" viewBox="0 0 150 100">
<polygon points="10,90 50,10 90,50 130,10" fill="#ffc107" stroke="#007bff" stroke-width="3"/>
</svg>
<ul>
<li>โ
Always closed</li>
<li>โ
Simple connected lines</li>
<li>โ No curves</li>
<li>โ
Always fills</li>
</ul>
</div>
<div class="comparison-card">
<h3>๐ค๏ธ Path</h3>
<svg width="150" height="100" viewBox="0 0 150 100">
<path d="M 10 90 C 40 10, 70 10, 90 50 C 110 90, 130 10, 140 10" fill="none" stroke="#007bff" stroke-width="3"/>
</svg>
<ul>
<li>โ
Open or closed</li>
<li>โ
Lines and curves</li>
<li>โ
Full control</li>
<li>โ
Most versatile</li>
</ul>
</div>
</div>
<!-- ====== SECTION 7: MORE PATH EXAMPLES ====== -->
<h2>7. More Path Examples</h2>
<div class="svg-container" style="flex-direction: column;">
<div class="grid-3">
<div class="shape-card">
<h4>Star</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<path d="M 60 10 L 70 50 L 110 50 L 80 75 L 90 110 L 60 90 L 30 110 L 40 75 L 10 50 L 50 50 Z"
fill="#ffc107" stroke="#007bff" stroke-width="2"/>
</svg>
</div>
<div class="shape-card">
<h4>Arc</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<path d="M 20 60 A 40 40 0 1 1 100 60" fill="none" stroke="#28a745" stroke-width="4"/>
<path d="M 20 60 A 40 40 0 0 0 100 60" fill="none" stroke="#dc3545" stroke-width="4"/>
</svg>
</div>
<div class="shape-card">
<h4>Wave</h4>
<svg width="120" height="120" viewBox="0 0 120 120">
<path d="M 10 60 Q 30 30, 50 60 T 90 60 T 110 60" fill="none" stroke="#6c5ce7" stroke-width="4"/>
</svg>
</div>
</div>
</div>
<!-- ====== SECTION 8: REFERENCE TABLES ====== -->
<h2>8. Quick Reference</h2>
<table class="reference-table">
<thead>
<tr>
<th>Element</th>
<th>Purpose</th>
<th>Key Attributes</th>
<th>Best For</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><ellipse></code></td>
<td>Ellipse/Circle</td>
<td><code>cx</code>, <code>cy</code>, <code>rx</code>, <code>ry</code></td>
<td>Ovals, circles</td>
</tr>
<tr>
<td><code><line></code></td>
<td>Straight line</td>
<td><code>x1</code>, <code>y1</code>, <code>x2</code>, <code>y2</code></td>
<td>Simple lines, rules</td>
</tr>
<tr>
<td><code><polyline></code></td>
<td>Connected lines</td>
<td><code>points</code></td>
<td>Zigzags, open paths</td>
</tr>
<tr>
<td><code><path></code></td>
<td>Complex shapes</td>
<td><code>d</code></td>
<td>Any shape (most versatile)</td>
</tr>
</tbody>
</table>
<!-- ====== SECTION 9: BEST PRACTICES ====== -->
<h2>9. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Use <code><ellipse></code> for <strong>ovals and circles</strong></li>
<li>Use <code><line></code> for <strong>simple straight lines</strong></li>
<li>Use <code><polyline></code> for <strong>zigzags and open shapes</strong></li>
<li>Use <code><path></code> for <strong>complex shapes</strong> with curves</li>
<li>Use <strong>lowercase commands</strong> in <code>d</code> attribute for clarity</li>
<li>Add <strong>comments</strong> to complex paths for readability</li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <code><polyline></code> for closed shapes โ use <code><polygon></code></li>
<li>Don't use <code><line></code> for <strong>thick shapes</strong> โ use <code><rect></code> instead</li>
<li>Don't use <code><path></code> for <strong>simple shapes</strong> โ use simpler elements</li>
<li>Don't use <strong>absolute coordinates</strong> without considering <code>viewBox</code></li>
<li>Don't forget to set <code>fill="none"</code> for open paths</li>
</ul>
</div>
</body>
</html>
Quick Reference
| Element | Purpose | Key Attributes | Example |
|---|---|---|---|
<ellipse> | Ellipse/Circle | cx, cy, rx, ry | <ellipse cx="50" cy="50" rx="30" ry="20"/> |
<line> | Straight line | x1, y1, x2, y2 | <line x1="10" y1="10" x2="90" y2="90"/> |
<polyline> | Connected lines | points | <polyline points="0,0 50,25 100,0"/> |
<path> | Complex shapes | d (commands) | <path d="M 10 10 L 90 90"/> |
Path Commands Cheat Sheet
| Command | Description | Example |
|---|---|---|
M x y | Move to | M 10 10 |
L x y | Line to | L 90 90 |
H x | Horizontal line | H 100 |
V y | Vertical line | V 100 |
C x1 y1, x2 y2, x y | Cubic Bezier | C 20 20, 80 20, 100 50 |
Q x1 y1, x y | Quadratic Bezier | Q 50 10, 90 90 |
A rx ry rot large sweep x y | Arc | A 40 40 0 1 1 100 60 |
Z | Close path | Z |
Pro Tip: The <path> element is the most powerful and flexible SVG element. While simpler elements like <rect>, <circle>, and <polyline> are easier to use, mastering <path> gives you complete control over any shape you can imagine!
27. The Canvas Element
The <canvas> element is a powerful HTML element used to draw graphics dynamically using JavaScript. Itโs ideal for creating animations, games, data visualizations, image editing, and more.
What is the Canvas Element?
The <canvas> element provides a drawing surface that you can control with JavaScript. Unlike SVG, which is declarative, canvas uses imperative programming โ you give step-by-step instructions to draw shapes, text, and images.
Key Characteristics:
- Requires JavaScript for drawing
- Immediate mode โ draws pixels, not objects
- Great for animations and games
- Resolution-dependent โ use
width/heightattributes for sizing - Transparent by default
Basic Syntax:
<canvas id="thecanvas" width="400" height="200"></canvas>
<script>
const cnv = document.getElementById('thecanvas');
const ctx = cnv.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 40);
</script>
Canvas Attributes
| Attribute | Purpose | Example |
|---|---|---|
id | Unique identifier for JavaScript | id="myCanvas" |
width | Width of the drawing area (in pixels) | width="400" |
height | Height of the drawing area (in pixels) | height="200" |
Important: Use the width and height attributes on the <canvas> element itself โ not CSS โ to set the canvas size. Using CSS will stretch the canvas instead of resizing the drawing surface.
Getting the Canvas Context
To draw on a canvas, you need to get the rendering context:
const canvas = document.getElementById('thecanvas');
const ctx = canvas.getContext('2d'); // For 2D graphics
For 3D graphics, you can use:
const gl = canvas.getContext('webgl'); // For WebGL
Canvas Drawing Basics
Filling a Rectangle:
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 40);
Stroking a Rectangle:
ctx.strokeStyle = 'blue';
ctx.strokeRect(100, 10, 50, 40);
Clearing a Rectangle:
ctx.clearRect(0, 0, canvas.width, canvas.height);
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Element</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.canvas-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
canvas {
border: 2px solid #ddd;
border-radius: 8px;
background: white;
display: block;
max-width: 100%;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
.code-block {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.95em;
line-height: 1.8;
margin: 10px 0;
}
.btn-group {
margin: 15px 0;
display: flex;
flex-wrap: wrap;
gap: 10px;
}
button {
background: #007bff;
color: white;
padding: 10px 25px;
border: none;
border-radius: 6px;
font-size: 1em;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
button.reset {
background: #6c757d;
}
button.reset:hover {
background: #545b62;
}
button.green {
background: #28a745;
}
button.green:hover {
background: #1e7e34;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.grid-2 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
</style>
</head>
<body>
<h1>Canvas Element</h1>
<!-- ====== SECTION 1: BASIC CANVAS ====== -->
<h2>1. Basic Canvas</h2>
<div class="canvas-container">
<canvas id="basicCanvas" width="400" height="150"></canvas>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><canvas</span> <span style="color: #9cdcfe;">id</span>=<span style="color: #ce9178;">"basicCanvas"</span> <span style="color: #9cdcfe;">width</span>=<span style="color: #ce9178;">"400"</span> <span style="color: #9cdcfe;">height</span>=<span style="color: #ce9178;">"150"</span><span style="color: #569cd6;">></canvas></span>
<span style="color: #6a9955;">// JavaScript</span>
<span style="color: #569cd6;">const</span> canvas = document.<span style="color: #dcdcaa;">getElementById</span>(<span style="color: #ce9178;">'basicCanvas'</span>);
<span style="color: #569cd6;">const</span> ctx = canvas.<span style="color: #dcdcaa;">getContext</span>(<span style="color: #ce9178;">'2d'</span>);
ctx.<span style="color: #dcdcaa;">fillStyle</span> = <span style="color: #ce9178;">'red'</span>;
ctx.<span style="color: #dcdcaa;">fillRect</span>(<span style="color: #b5cea8;">10</span>, <span style="color: #b5cea8;">10</span>, <span style="color: #b5cea8;">50</span>, <span style="color: #b5cea8;">40</span>);
</div>
</div>
</div>
<!-- ====== SECTION 2: DRAWING SHAPES ====== -->
<h2>2. Drawing Shapes</h2>
<div class="canvas-container">
<canvas id="shapesCanvas" width="500" height="200"></canvas>
<div class="example-box">
<h4>๐ Shapes Drawn:</h4>
<ul>
<li>๐ด Red filled rectangle</li>
<li>๐ต Blue stroked rectangle</li>
<li>๐ข Green filled circle</li>
<li>๐ Orange stroked circle</li>
<li>๐ฃ Purple filled triangle (path)</li>
</ul>
</div>
</div>
<!-- ====== SECTION 3: DRAWING PATHS ====== -->
<h2>3. Drawing Paths</h2>
<div class="canvas-container">
<canvas id="pathsCanvas" width="500" height="200"></canvas>
<div class="example-box">
<h4>๐ Paths Drawn:</h4>
<ul>
<li>๐ท Star shape (filled)</li>
<li>๐ถ Triangle (stroked)</li>
<li>๐ฌ Heart shape (filled)</li>
</ul>
</div>
</div>
<!-- ====== SECTION 4: ANIMATION ====== -->
<h2>4. Animation</h2>
<div class="canvas-container">
<canvas id="animationCanvas" width="500" height="250"></canvas>
<div class="btn-group">
<button id="startAnimation">โถ Start Animation</button>
<button id="stopAnimation" class="reset">โน Stop</button>
<button id="resetAnimation" class="reset">๐ Reset</button>
</div>
<div class="example-box">
<h4>๐ How it works:</h4>
<ul>
<li>A circle moves across the canvas</li>
<li>Uses <code>requestAnimationFrame()</code> for smooth animation</li>
<li>The canvas is cleared and redrawn each frame</li>
</ul>
</div>
</div>
<!-- ====== SECTION 5: DRAWING TEXT ====== -->
<h2>5. Drawing Text</h2>
<div class="canvas-container">
<canvas id="textCanvas" width="500" height="150"></canvas>
<div class="example-box">
<h4>๐ Text Examples:</h4>
<ul>
<li>๐ Styled text with custom font</li>
<li>๐จ Filled and stroked text</li>
<li>๐ Text alignment (center, right, left)</li>
</ul>
</div>
</div>
<!-- ====== SECTION 6: GRADIENTS ====== -->
<h2>6. Gradients</h2>
<div class="canvas-container">
<canvas id="gradientCanvas" width="500" height="200"></canvas>
<div class="example-box">
<h4>๐ Gradient Types:</h4>
<ul>
<li>๐ Linear gradient (blue to purple)</li>
<li>๐ต Radial gradient (center to edge)</li>
<li>๐จ Gradient used on shapes and rectangles</li>
</ul>
</div>
</div>
<!-- ====== SECTION 7: IMAGE ====== -->
<h2>7. Drawing Images</h2>
<div class="canvas-container">
<canvas id="imageCanvas" width="400" height="150"></canvas>
<div class="example-box">
<h4>๐ Image Drawing:</h4>
<ul>
<li>๐ผ๏ธ Draws an image onto the canvas</li>
<li>๐ Scales the image to fit</li>
<li>๐จ Images can be manipulated pixel by pixel</li>
</ul>
</div>
</div>
<!-- ====== SECTION 8: REFERENCE TABLE ====== -->
<h2>8. Canvas API Reference</h2>
<h3>Common Methods</h3>
<table class="reference-table">
<thead>
<tr>
<th>Method</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>fillRect(x, y, w, h)</code></td>
<td>Draws a filled rectangle</td>
<td><code>ctx.fillRect(10, 10, 50, 40)</code></td>
</tr>
<tr>
<td><code>strokeRect(x, y, w, h)</code></td>
<td>Draws a stroked rectangle</td>
<td><code>ctx.strokeRect(70, 10, 50, 40)</code></td>
</tr>
<tr>
<td><code>clearRect(x, y, w, h)</code></td>
<td>Clears a rectangle area</td>
<td><code>ctx.clearRect(0, 0, 400, 200)</code></td>
</tr>
<tr>
<td><code>beginPath()</code></td>
<td>Starts a new path</td>
<td><code>ctx.beginPath()</code></td>
</tr>
<tr>
<td><code>arc(x, y, r, s, e)</code></td>
<td>Draws an arc (circle)</td>
<td><code>ctx.arc(100, 100, 40, 0, Math.PI * 2)</code></td>
</tr>
<tr>
<td><code>fill()</code></td>
<td>Fills the current path</td>
<td><code>ctx.fill()</code></td>
</tr>
<tr>
<td><code>stroke()</code></td>
<td>Strokes the current path</td>
<td><code>ctx.stroke()</code></td>
</tr>
</tbody>
</table>
<h3>Common Properties</h3>
<table class="reference-table">
<thead>
<tr>
<th>Property</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>fillStyle</code></td>
<td>Fill color or gradient</td>
<td><code>ctx.fillStyle = 'red'</code></td>
</tr>
<tr>
<td><code>strokeStyle</code></td>
<td>Stroke color or gradient</td>
<td><code>ctx.strokeStyle = 'blue'</code></td>
</tr>
<tr>
<td><code>lineWidth</code></td>
<td>Line thickness</td>
<td><code>ctx.lineWidth = 3</code></td>
</tr>
<tr>
<td><code>font</code></td>
<td>Font for text</td>
<td><code>ctx.font = '20px Arial'</code></td>
</tr>
<tr>
<td><code>textAlign</code></td>
<td>Text alignment</td>
<td><code>ctx.textAlign = 'center'</code></td>
</tr>
</tbody>
</table>
<!-- ====== SECTION 9: BEST PRACTICES ====== -->
<h2>9. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Set <code>width</code> and <code>height</code> as <strong>HTML attributes</strong>, not CSS</li>
<li>Use <code>requestAnimationFrame()</code> for <strong>smooth animations</strong></li>
<li>Save canvas state with <code>save()</code> and restore with <code>restore()</code></li>
<li>Use <strong>off-screen canvases</strong> for complex pre-rendering</li>
<li>For high-DPI displays, <strong>scale the canvas</strong> using <code>devicePixelRatio</code></li>
<li>Always provide a <strong>fallback message</strong> inside the canvas tag</li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use CSS to set canvas <strong>width/height</strong> (use HTML attributes)</li>
<li>Don't forget to <code>beginPath()</code> before drawing a new shape</li>
<li>Don't use canvas for <strong>simple static graphics</strong> (use SVG or CSS)</li>
<li>Don't draw in the canvas <strong>before the page loads</strong></li>
<li>Don't forget to clear the canvas when <strong>animating</strong></li>
</ul>
</div>
</body>
</html>
<script>
// ============================================================
// 1. BASIC CANVAS
// ============================================================
const basicCanvas = document.getElementById('basicCanvas');
const basicCtx = basicCanvas.getContext('2d');
basicCtx.fillStyle = 'red';
basicCtx.fillRect(10, 10, 50, 40);
basicCtx.fillStyle = 'blue';
basicCtx.fillRect(80, 10, 50, 40);
basicCtx.fillStyle = 'green';
basicCtx.fillRect(150, 10, 50, 40);
basicCtx.fillStyle = 'orange';
basicCtx.fillRect(220, 10, 50, 40);
basicCtx.fillStyle = 'purple';
basicCtx.fillRect(290, 10, 50, 40);
// ============================================================
// 2. DRAWING SHAPES
// ============================================================
const shapesCanvas = document.getElementById('shapesCanvas');
const shapesCtx = shapesCanvas.getContext('2d');
// Filled rectangle
shapesCtx.fillStyle = 'red';
shapesCtx.fillRect(10, 20, 60, 40);
// Stroked rectangle
shapesCtx.strokeStyle = 'blue';
shapesCtx.lineWidth = 3;
shapesCtx.strokeRect(90, 20, 60, 40);
// Filled circle
shapesCtx.beginPath();
shapesCtx.fillStyle = 'green';
shapesCtx.arc(190, 50, 30, 0, Math.PI * 2);
shapesCtx.fill();
// Stroked circle
shapesCtx.beginPath();
shapesCtx.strokeStyle = 'orange';
shapesCtx.lineWidth = 4;
shapesCtx.arc(270, 50, 30, 0, Math.PI * 2);
shapesCtx.stroke();
// Filled triangle (path)
shapesCtx.beginPath();
shapesCtx.fillStyle = 'purple';
shapesCtx.moveTo(360, 20);
shapesCtx.lineTo(330, 70);
shapesCtx.lineTo(390, 70);
shapesCtx.closePath();
shapesCtx.fill();
// Stroked triangle
shapesCtx.beginPath();
shapesCtx.strokeStyle = 'magenta';
shapesCtx.lineWidth = 3;
shapesCtx.moveTo(440, 20);
shapesCtx.lineTo(410, 70);
shapesCtx.lineTo(470, 70);
shapesCtx.closePath();
shapesCtx.stroke();
// ============================================================
// 3. DRAWING PATHS
// ============================================================
const pathsCanvas = document.getElementById('pathsCanvas');
const pathsCtx = pathsCanvas.getContext('2d');
// Star
pathsCtx.beginPath();
const cx = 80, cy = 80;
const outerR = 60, innerR = 25;
const points = 5;
for (let i = 0; i < points * 2; i++) {
const radius = i % 2 === 0 ? outerR : innerR;
const angle = (i / (points * 2)) * Math.PI * 2 - Math.PI / 2;
const x = cx + radius * Math.cos(angle);
const y = cy + radius * Math.sin(angle);
if (i === 0) pathsCtx.moveTo(x, y);
else pathsCtx.lineTo(x, y);
}
pathsCtx.closePath();
pathsCtx.fillStyle = '#ffc107';
pathsCtx.strokeStyle = '#007bff';
pathsCtx.lineWidth = 3;
pathsCtx.fill();
pathsCtx.stroke();
// Triangle
pathsCtx.beginPath();
pathsCtx.moveTo(220, 20);
pathsCtx.lineTo(180, 80);
pathsCtx.lineTo(260, 80);
pathsCtx.closePath();
pathsCtx.strokeStyle = '#dc3545';
pathsCtx.lineWidth = 4;
pathsCtx.stroke();
// Heart
pathsCtx.beginPath();
pathsCtx.moveTo(360, 40);
pathsCtx.bezierCurveTo(330, 10, 290, 30, 360, 70);
pathsCtx.moveTo(360, 40);
pathsCtx.bezierCurveTo(390, 10, 430, 30, 360, 70);
pathsCtx.fillStyle = '#dc3545';
pathsCtx.fill();
// ============================================================
// 4. ANIMATION
// ============================================================
const animCanvas = document.getElementById('animationCanvas');
const animCtx = animCanvas.getContext('2d');
let animX = 50;
let animY = 100;
let animDx = 2;
let animId = null;
function drawAnimation() {
// Clear canvas
animCtx.clearRect(0, 0, animCanvas.width, animCanvas.height);
// Draw background
animCtx.fillStyle = '#f0f0f0';
animCtx.fillRect(0, 0, animCanvas.width, animCanvas.height);
// Draw circle
const gradient = animCtx.createRadialGradient(animX, animY, 10, animX, animY, 40);
gradient.addColorStop(0, '#ff6b6b');
gradient.addColorStop(1, '#c92a2a');
animCtx.beginPath();
animCtx.arc(animX, animY, 35, 0, Math.PI * 2);
animCtx.fillStyle = gradient;
animCtx.fill();
animCtx.strokeStyle = '#333';
animCtx.lineWidth = 2;
animCtx.stroke();
// Update position
animX += animDx;
if (animX > animCanvas.width - 35 || animX < 35) {
animDx = -animDx;
}
animId = requestAnimationFrame(drawAnimation);
}
let animationRunning = false;
document.getElementById('startAnimation').addEventListener('click', function() {
if (!animationRunning) {
animationRunning = true;
drawAnimation();
}
});
document.getElementById('stopAnimation').addEventListener('click', function() {
if (animationRunning) {
animationRunning = false;
cancelAnimationFrame(animId);
}
});
document.getElementById('resetAnimation').addEventListener('click', function() {
if (animationRunning) {
animationRunning = false;
cancelAnimationFrame(animId);
}
animX = 50;
animId = null;
animCtx.clearRect(0, 0, animCanvas.width, animCanvas.height);
animCtx.fillStyle = '#f0f0f0';
animCtx.fillRect(0, 0, animCanvas.width, animCanvas.height);
animCtx.beginPath();
animCtx.arc(animX, animY, 35, 0, Math.PI * 2);
animCtx.fillStyle = '#ff6b6b';
animCtx.fill();
animCtx.strokeStyle = '#333';
animCtx.lineWidth = 2;
animCtx.stroke();
});
// Initial draw
animCtx.fillStyle = '#f0f0f0';
animCtx.fillRect(0, 0, animCanvas.width, animCanvas.height);
animCtx.beginPath();
animCtx.arc(animX, animY, 35, 0, Math.PI * 2);
animCtx.fillStyle = '#ff6b6b';
animCtx.fill();
animCtx.strokeStyle = '#333';
animCtx.lineWidth = 2;
animCtx.stroke();
// ============================================================
// 5. DRAWING TEXT
// ============================================================
const textCanvas = document.getElementById('textCanvas');
const textCtx = textCanvas.getContext('2d');
// Filled text
textCtx.font = 'bold 24px Arial';
textCtx.fillStyle = '#007bff';
textCtx.fillText('Hello, Canvas!', 20, 50);
// Stroked text
textCtx.font = '24px Arial';
textCtx.strokeStyle = '#dc3545';
textCtx.lineWidth = 1;
textCtx.strokeText('Hello, Canvas!', 20, 90);
// Centered text
textCtx.font = '18px Arial';
textCtx.textAlign = 'center';
textCtx.fillStyle = '#28a745';
textCtx.fillText('Centered Text', 350, 50);
// Right-aligned text
textCtx.textAlign = 'right';
textCtx.fillStyle = '#6c5ce7';
textCtx.fillText('Right Aligned', 480, 90);
// Shadow text
textCtx.shadowColor = 'rgba(0,0,0,0.3)';
textCtx.shadowBlur = 5;
textCtx.shadowOffsetX = 3;
textCtx.shadowOffsetY = 3;
textCtx.font = 'bold 20px Arial';
textCtx.fillStyle = '#ffc107';
textCtx.fillText('Shadow Text', 20, 130);
textCtx.shadowColor = 'transparent';
// ============================================================
// 6. GRADIENTS
// ============================================================
const gradCanvas = document.getElementById('gradientCanvas');
const gradCtx = gradCanvas.getContext('2d');
// Linear gradient
const linearGrad = gradCtx.createLinearGradient(0, 0, 200, 0);
linearGrad.addColorStop(0, '#007bff');
linearGrad.addColorStop(0.5, '#6c5ce7');
linearGrad.addColorStop(1, '#dc3545');
gradCtx.fillStyle = linearGrad;
gradCtx.fillRect(10, 20, 180, 60);
// Horizontal text with gradient
gradCtx.font = 'bold 24px Arial';
gradCtx.fillStyle = linearGrad;
gradCtx.fillText('Gradient Text', 210, 65);
// Radial gradient
const radialGrad = gradCtx.createRadialGradient(400, 50, 10, 400, 50, 50);
radialGrad.addColorStop(0, '#ffc107');
radialGrad.addColorStop(1, '#dc3545');
gradCtx.fillStyle = radialGrad;
gradCtx.beginPath();
gradCtx.arc(400, 50, 45, 0, Math.PI * 2);
gradCtx.fill();
// Rectangle with gradient
const rectGrad = gradCtx.createLinearGradient(10, 100, 200, 150);
rectGrad.addColorStop(0, '#28a745');
rectGrad.addColorStop(0.5, '#ffc107');
rectGrad.addColorStop(1, '#dc3545');
gradCtx.fillStyle = rectGrad;
gradCtx.fillRect(10, 100, 200, 50);
// ============================================================
// 7. IMAGE
// ============================================================
const imgCanvas = document.getElementById('imageCanvas');
const imgCtx = imgCanvas.getContext('2d');
// Create an image
const img = new Image();
img.src = 'https://via.placeholder.com/200x100/007bff/ffffff?text=Canvas+Image';
img.onload = function() {
imgCtx.drawImage(img, 10, 20, 180, 80);
// Add text overlay
imgCtx.font = 'bold 14px Arial';
imgCtx.fillStyle = 'white';
imgCtx.textAlign = 'center';
imgCtx.fillText('Image on Canvas', 100, 70);
};
</script>
Canvas vs SVG Comparison
| Feature | Canvas | SVG |
|---|---|---|
| Rendering | Immediate (pixel-based) | Retained (DOM-based) |
| Performance | Better for complex animations | Better for static graphics |
| Scalability | Pixelated when scaled | Scalable without quality loss |
| Interactivity | Requires JavaScript | Supports CSS and JS events |
| Accessibility | Poor (no semantic content) | Good (accessible DOM) |
| Best For | Games, animations, pixel effects | Icons, logos, data visualizations |
Common Canvas Use Cases
| Use Case | Description |
|---|---|
| Games | Real-time graphics rendering |
| Animations | Smooth, frame-based animations |
| Data Visualization | Charts, graphs, diagrams |
| Image Editing | Filters, cropping, manipulation |
| Pixel Art | Drawing at the pixel level |
| Interactive Graphics | Drawing apps, whiteboards |
Pro Tip: The canvas element is perfect for dynamic, interactive, and animated graphics. Use requestAnimationFrame() for smooth animations, and always clear the canvas before redrawing each frame. For static graphics that need to be scalable, prefer SVG instead!
28. Mathematical Markup Language (MathML)
MathML (Mathematical Markup Language) is an XML-based markup language used to describe mathematical notations and formulas. It allows you to embed complex mathematical expressions directly into web pages in a structured, accessible way.
What is MathML?
MathML is designed to integrate mathematical formulas into websites, making them machine-readable, accessible to screen readers, and renderable by browsers.
Key Characteristics:
- XML-based markup language
- Can be directly embedded in HTML5
- Modern browsers support MathML natively
- Accessible โ screen readers can interpret and read formulas aloud
- Semantic โ describes the structure of mathematical expressions
Basic Syntax:
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>x</mi>
<mo>=</mo>
<mfrac>
<mrow>
<mo>-</mo>
<mi>b</mi>
<mo>ยฑ</mo>
<msqrt>
<msup><mi>b</mi><mn>2</mn></msup>
<mo>-</mo>
<mn>4</mn>
<mi>a</mi>
<mi>c</mi>
</msqrt>
</mrow>
<mrow>
<mn>2</mn>
<mi>a</mi>
</mrow>
</mfrac>
</mrow>
</math>
This renders as the quadratic formula:
x = (-b ยฑ โ(bยฒ – 4ac)) / 2a
MathML Elements
Core Elements
| Element | Purpose | Description |
|---|---|---|
<math> | Root element | Container for the entire MathML expression |
<mrow> | Horizontal group | Groups elements horizontally (like parentheses) |
<mi> | Math identifier | Variables (e.g., x, y, a, b) |
<mo> | Math operator | Operators (e.g., +, โ, ร, รท, =, ยฑ, โ) |
<mn> | Math number | Numerical literals (e.g., 2, 4, 10) |
<mfrac> | Fraction | Numerator and denominator |
<msqrt> | Square root | Square root of an expression |
<msup> | Superscript | Base and exponent (e.g., xยฒ) |
<msub> | Subscript | Base and subscript (e.g., xโ) |
<mtable> | Table | Matrix or array |
<mtr> | Table row | Row in a matrix |
<mtd> | Table cell | Cell in a matrix |
Common MathML Elements
1. Basic Math Identifiers & Operators
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>E</mi>
<mo>=</mo>
<mi>m</mi>
<msup>
<mi>c</mi>
<mn>2</mn>
</msup>
</mrow>
</math>
E = mcยฒ
2. Fractions
<math>
<mfrac>
<mn>1</mn>
<mn>2</mn>
</mfrac>
</math>
ยฝ
3. Square Root
<math>
<msqrt>
<mn>2</mn>
</msqrt>
</math>
โ2
4. Subscript
<math>
<msub>
<mi>H</mi>
<mn>2</mn>
</msub>
<mi>O</mi>
</math>
HโO
5. Superscript
<math>
<msup>
<mi>a</mi>
<mn>2</mn>
</msup>
<mo>+</mo>
<msup>
<mi>b</mi>
<mn>2</mn>
</msup>
<mo>=</mo>
<msup>
<mi>c</mi>
<mn>2</mn>
</msup>
</math>
aยฒ + bยฒ = cยฒ
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MathML - Mathematical Markup Language</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.8;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.math-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
text-align: center;
}
.math-container math {
font-size: 1.5em;
padding: 15px;
display: inline-block;
background: #f8f9fa;
border-radius: 8px;
min-width: 100px;
}
.grid-2 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin: 20px 0;
}
.example-box {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
text-align: left;
}
.code-block {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9em;
line-height: 1.8;
margin: 10px 0;
text-align: left;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.badge {
display: inline-block;
background: #28a745;
color: white;
padding: 2px 12px;
border-radius: 20px;
font-size: 0.8em;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Mathematical Markup Language (MathML)</h1>
<!-- ====== SECTION 1: QUADRATIC FORMULA ====== -->
<h2>1. Quadratic Formula</h2>
<div class="math-container">
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>x</mi>
<mo>=</mo>
<mfrac>
<mrow>
<mo>โ</mo>
<mi>b</mi>
<mo>ยฑ</mo>
<msqrt>
<msup>
<mi>b</mi>
<mn>2</mn>
</msup>
<mo>โ</mo>
<mn>4</mn>
<mi>a</mi>
<mi>c</mi>
</msqrt>
</mrow>
<mrow>
<mn>2</mn>
<mi>a</mi>
</mrow>
</mfrac>
</mrow>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math</span> <span style="color: #9cdcfe;">xmlns</span>=<span style="color: #ce9178;">"http://www.w3.org/1998/Math/MathML"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <mi></span>x<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mo></span>=<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mfrac></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <mo></span>โ<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mi></span>b<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mo></span>ยฑ<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <msqrt></span>
<span style="color: #569cd6;"> <msup></span>
<span style="color: #569cd6;"> <mi></span>b<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mn></span>2<span style="color: #569cd6;"></mn></span>
<span style="color: #569cd6;"> </msup></span>
<span style="color: #569cd6;"> <mo></span>โ<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mn></span>4<span style="color: #569cd6;"></mn></span>
<span style="color: #569cd6;"> <mi></span>a<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mi></span>c<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> </msqrt></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <mn></span>2<span style="color: #569cd6;"></mn></span>
<span style="color: #569cd6;"> <mi></span>a<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"> </mfrac></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
<!-- ====== SECTION 2: COMMON FORMULAS ====== -->
<h2>2. Common Mathematical Formulas</h2>
<div class="grid-2">
<!-- Pythagorean Theorem -->
<div class="math-container">
<h3>Pythagorean Theorem</h3>
<math>
<mrow>
<msup>
<mi>a</mi>
<mn>2</mn>
</msup>
<mo>+</mo>
<msup>
<mi>b</mi>
<mn>2</mn>
</msup>
<mo>=</mo>
<msup>
<mi>c</mi>
<mn>2</mn>
</msup>
</mrow>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <msup><mi></span>a<span style="color: #569cd6;"></mi><mn></span>2<span style="color: #569cd6;"></mn></msup></span>
<span style="color: #569cd6;"> <mo></span>+<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <msup><mi></span>b<span style="color: #569cd6;"></mi><mn></span>2<span style="color: #569cd6;"></mn></msup></span>
<span style="color: #569cd6;"> <mo></span>=<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <msup><mi></span>c<span style="color: #569cd6;"></mi><mn></span>2<span style="color: #569cd6;"></mn></msup></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
<!-- Einstein's Equation -->
<div class="math-container">
<h3>Einstein's Mass-Energy Equivalence</h3>
<math>
<mrow>
<mi>E</mi>
<mo>=</mo>
<mi>m</mi>
<msup>
<mi>c</mi>
<mn>2</mn>
</msup>
</mrow>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <mi></span>E<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mo></span>=<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mi></span>m<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <msup><mi></span>c<span style="color: #569cd6;"></mi><mn></span>2<span style="color: #569cd6;"></mn></msup></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
<!-- Chemical Formula -->
<div class="math-container">
<h3>Chemical Formula (Water)</h3>
<math>
<mrow>
<msub>
<mi>H</mi>
<mn>2</mn>
</msub>
<mi>O</mi>
</mrow>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <msub></span>
<span style="color: #569cd6;"> <mi></span>H<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mn></span>2<span style="color: #569cd6;"></mn></span>
<span style="color: #569cd6;"> </msub></span>
<span style="color: #569cd6;"> <mi></span>O<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
<!-- Derivative -->
<div class="math-container">
<h3>Derivative</h3>
<math>
<mfrac>
<mrow>
<mi>d</mi>
<mi>f</mi>
</mrow>
<mrow>
<mi>d</mi>
<mi>x</mi>
</mrow>
</mfrac>
<mo>=</mo>
<mn>2</mn>
<mi>x</mi>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math></span>
<span style="color: #569cd6;"> <mfrac></span>
<span style="color: #569cd6;"> <mrow><mi></span>d<span style="color: #569cd6;"></mi><mi></span>f<span style="color: #569cd6;"></mi></mrow></span>
<span style="color: #569cd6;"> <mrow><mi></span>d<span style="color: #569cd6;"></mi><mi></span>x<span style="color: #569cd6;"></mi></mrow></span>
<span style="color: #569cd6;"> </mfrac></span>
<span style="color: #569cd6;"> <mo></span>=<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mn></span>2<span style="color: #569cd6;"></mn></span>
<span style="color: #569cd6;"> <mi></span>x<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
</div>
<!-- ====== SECTION 3: COMPLEX EXPRESSIONS ====== -->
<h2>3. Complex Expressions</h2>
<div class="grid-2">
<!-- Summation -->
<div class="math-container">
<h3>Summation</h3>
<math>
<mrow>
<munderover>
<mo>โ</mo>
<mrow>
<mi>i</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mi>n</mi>
</munderover>
<msup>
<mi>i</mi>
<mn>2</mn>
</msup>
</mrow>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <munderover></span>
<span style="color: #569cd6;"> <mo></span>โ<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mrow><mi></span>i<span style="color: #569cd6;"></mi><mo></span>=<span style="color: #569cd6;"></mo><mn></span>1<span style="color: #569cd6;"></mn></mrow></span>
<span style="color: #569cd6;"> <mi></span>n<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> </munderover></span>
<span style="color: #569cd6;"> <msup><mi></span>i<span style="color: #569cd6;"></mi><mn></span>2<span style="color: #569cd6;"></mn></msup></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
<!-- Integral -->
<div class="math-container">
<h3>Integral</h3>
<math>
<mrow>
<msubsup>
<mo>โซ</mo>
<mn>0</mn>
<mn>โ</mn>
</msubsup>
<msup>
<mi>e</mi>
<mrow>
<mo>โ</mo>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
</mrow>
</msup>
<mi>d</mi>
<mi>x</mi>
</mrow>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <msubsup></span>
<span style="color: #569cd6;"> <mo></span>โซ<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mn></span>0<span style="color: #569cd6;"></mn></span>
<span style="color: #569cd6;"> <mn></span>โ<span style="color: #569cd6;"></mn></span>
<span style="color: #569cd6;"> </msubsup></span>
<span style="color: #569cd6;"> <msup></span>
<span style="color: #569cd6;"> <mi></span>e<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mrow><mo></span>โ<span style="color: #569cd6;"></mo><msup><mi></span>x<span style="color: #569cd6;"></mi><mn></span>2<span style="color: #569cd6;"></mn></msup></mrow></span>
<span style="color: #569cd6;"> </msup></span>
<span style="color: #569cd6;"> <mi></span>d<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> <mi></span>x<span style="color: #569cd6;"></mi></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
</div>
<!-- ====== SECTION 4: MATRICES ====== -->
<h2>4. Matrices</h2>
<div class="math-container">
<h3>2ร2 Matrix</h3>
<math>
<mrow>
<mo>[</mo>
<mtable>
<mtr>
<mtd><mi>a</mi></mtd>
<mtd><mi>b</mi></mtd>
</mtr>
<mtr>
<mtd><mi>c</mi></mtd>
<mtd><mi>d</mi></mtd>
</mtr>
</mtable>
<mo>]</mo>
</mrow>
</math>
<div class="example-box">
<h4>๐ Code:</h4>
<div class="code-block">
<span style="color: #569cd6;"><math></span>
<span style="color: #569cd6;"> <mrow></span>
<span style="color: #569cd6;"> <mo></span>[<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> <mtable></span>
<span style="color: #569cd6;"> <mtr></span>
<span style="color: #569cd6;"> <mtd><mi></span>a<span style="color: #569cd6;"></mi></mtd></span>
<span style="color: #569cd6;"> <mtd><mi></span>b<span style="color: #569cd6;"></mi></mtd></span>
<span style="color: #569cd6;"> </mtr></span>
<span style="color: #569cd6;"> <mtr></span>
<span style="color: #569cd6;"> <mtd><mi></span>c<span style="color: #569cd6;"></mi></mtd></span>
<span style="color: #569cd6;"> <mtd><mi></span>d<span style="color: #569cd6;"></mi></mtd></span>
<span style="color: #569cd6;"> </mtr></span>
<span style="color: #569cd6;"> </mtable></span>
<span style="color: #569cd6;"> <mo></span>]<span style="color: #569cd6;"></mo></span>
<span style="color: #569cd6;"> </mrow></span>
<span style="color: #569cd6;"></math></span>
</div>
</div>
</div>
<!-- ====== SECTION 5: ELEMENT REFERENCE ====== -->
<h2>5. MathML Element Reference</h2>
<table class="reference-table">
<thead>
<tr>
<th>Element</th>
<th>Purpose</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><math></code></td>
<td>Root element</td>
<td><code><math>...</math></code></td>
</tr>
<tr>
<td><code><mrow></code></td>
<td>Horizontal group</td>
<td><code><mrow><mi>a</mi><mo>+</mo><mi>b</mi></mrow></code></td>
</tr>
<tr>
<td><code><mi></code></td>
<td>Math identifier (variable)</td>
<td><code><mi>x</mi></code></td>
</tr>
<tr>
<td><code><mo></code></td>
<td>Math operator</td>
<td><code><mo>=</mo></code></td>
</tr>
<tr>
<td><code><mn></code></td>
<td>Math number</td>
<td><code><mn>2</mn></code></td>
</tr>
<tr>
<td><code><mfrac></code></td>
<td>Fraction</td>
<td><code><mfrac><mn>1</mn><mn>2</mn></mfrac></code></td>
</tr>
<tr>
<td><code><msqrt></code></td>
<td>Square root</td>
<td><code><msqrt><mn>2</mn></msqrt></code></td>
</tr>
<tr>
<td><code><msup></code></td>
<td>Superscript</td>
<td><code><msup><mi>x</mi><mn>2</mn></msup></code></td>
</tr>
<tr>
<td><code><msub></code></td>
<td>Subscript</td>
<td><code><msub><mi>H</mi><mn>2</mn></msub></code></td>
</tr>
<tr>
<td><code><mtable></code></td>
<td>Table (matrix)</td>
<td><code><mtable>...</mtable></code></td>
</tr>
<tr>
<td><code><mtr></code></td>
<td>Table row</td>
<td><code><mtr>...</mtr></code></td>
</tr>
<tr>
<td><code><mtd></code></td>
<td>Table cell</td>
<td><code><mtd><mi>a</mi></mtd></code></td>
</tr>
</tbody>
</table>
<!-- ====== SECTION 6: BEST PRACTICES ====== -->
<h2>6. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Include the <strong>XML namespace</strong> in the <code><math></code> tag</li>
<li>Use <strong>semantic elements</strong> to describe the structure of the formula</li>
<li>Use <code><mrow></code> to group elements as needed</li>
<li>Test formulas in <strong>multiple browsers</strong> for compatibility</li>
<li>Provide a <strong>text alternative</strong> for formulas as needed</li>
<li>Use <strong>screen reader testing</strong> to ensure accessibility</li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <strong>images</strong> for formulas when MathML is available</li>
<li>Don't forget to close all <strong>MathML tags</strong></li>
<li>Don't use <strong>presentational</strong> MathML when semantic is possible</li>
<li>Don't rely on <strong>MathML</strong> for complex visual rendering without fallback</li>
<li>Don't use <strong>inline CSS</strong> to style MathML โ use browser-native rendering</li>
</ul>
</div>
<!-- ====== SECTION 7: ACCESSIBILITY ====== -->
<h2>7. Accessibility</h2>
<div class="math-container" style="text-align: left;">
<div class="example-box">
<h4>โฟ MathML and Screen Readers</h4>
<p>
MathML is designed to be <strong>accessible</strong> to screen readers. Properly structured MathML allows assistive technologies to:
</p>
<ul>
<li><strong>Read formulas aloud</strong> with correct mathematical pronunciation</li>
<li><strong>Navigate</strong> through complex expressions</li>
<li><strong>Provide</strong> alternative presentations</li>
</ul>
<p>
<strong>Example:</strong> The quadratic formula above would be read as:
<br>
<em>"x equals negative b plus or minus the square root of b squared minus four a c, all over two a."</em>
</p>
</div>
</div>
</body>
</html>
Quick Reference
| Element | Purpose | Description |
|---|---|---|
<math> | Root element | Container for all MathML content |
<mrow> | Horizontal group | Groups elements horizontally |
<mi> | Math identifier | Variables (x, y, a, b, etc.) |
<mo> | Math operator | +, โ, ร, รท, =, ยฑ, โ, etc. |
<mn> | Math number | Numerical literals (2, 4, 10, etc.) |
<mfrac> | Fraction | Numerator and denominator |
<msqrt> | Square root | Square root of an expression |
<msup> | Superscript | Base and exponent (xยฒ) |
<msub> | Subscript | Base and subscript (xโ) |
<mtable> | Table/Matrix | Matrix or array structure |
<mtr> | Table row | Row in a matrix |
<mtd> | Table cell | Cell in a matrix |
Common MathML Expressions
| Expression | MathML Code |
|---|---|
| Quadratic Formula | x = (-b ยฑ โ(bยฒ โ 4ac)) / 2a |
| Pythagorean Theorem | aยฒ + bยฒ = cยฒ |
| Einstein’s Equation | E = mcยฒ |
| Summation | โแตขโโโฟ iยฒ |
| Derivative | df/dx = 2x |
| Matrix | [a b; c d] |
Pro Tip: MathML is the best way to display mathematical formulas on the web. It’s accessible, semantic, and browser-native. While not all browsers support it perfectly, modern browsers like Chrome, Firefox, Safari, and Edge all support MathML. Use it to make your math content more accessible and maintainable!
29. Microdata
Microdata is a way to add structured data to HTML documents. It helps search engines understand the content of your page, enables rich snippets in search results, and improves accessibility for screen readers.
What is Microdata?
Microdata uses attributes added to HTML elements that provide additional semantic information. It defines a vocabulary of name-value pairs that describe the content.
Key Benefits:
| Benefit | Description |
|---|---|
| SEO | Improves search engine understanding and rankings |
| Rich Snippets | Enables enhanced search results (ratings, prices, etc.) |
| Accessibility | Better context for screen readers |
| Interoperability | Machine-readable data for apps and services |
Microdata Attributes
| Attribute | Purpose | Example |
|---|---|---|
itemscope | Creates a new item โ indicates the enclosed HTML block contains information about a single item | itemscope |
itemtype | Specifies the type of item being described (usually a URL from schema.org) | itemtype="https://schema.org/Person" |
itemprop | Indicates that the content is a property name of the item | itemprop="name" |
Basic Example
<div itemscope itemtype="https://schema.org/Person">
<span itemprop="name">Kronos</span>
<span itemprop="jobTitle">Fullstack Developer</span>
<a href="mailto:johndoe@example.com" itemprop="email">something@example.com</a>
</div>
Common Schema.org Types
| Type | Description | Example Properties |
|---|---|---|
Person | A person | name, jobTitle, email, address, birthDate |
Article | A news article | headline, author, datePublished, articleBody |
Book | A book | name, author, isbn, datePublished |
Movie | A movie | name, director, actors, duration |
Recipe | A recipe | name, recipeIngredient, recipeInstructions, cookTime |
Review | A review | reviewRating, reviewBody, author |
WebPage | A webpage | name, description, url, breadcrumb |
Organization | An organization | name, url, logo, address |
LocalBusiness | A local business | name, address, telephone, openingHours |
Product | A product | name, description, image, offers |
Event | An event | name, startDate, location, performer |
Place | A place | name, address, geo |
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microdata - Structured Data</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
line-height: 1.6;
}
h1 {
color: #007bff;
border-bottom: 3px solid #007bff;
padding-bottom: 10px;
}
h2 {
color: #28a745;
margin-top: 30px;
border-left: 4px solid #28a745;
padding-left: 15px;
}
.demo-container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
.demo-container .microdata-example {
background: #e9ecef;
padding: 15px;
border-radius: 6px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
.code-block {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.95em;
line-height: 1.8;
margin: 10px 0;
}
.reference-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.reference-table th,
.reference-table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
.reference-table th {
background: #007bff;
color: white;
}
.reference-table tr:nth-child(even) {
background: #f8f9fa;
}
.reference-table tr:hover {
background: #e9ecef;
}
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.95em;
color: #dc3545;
}
.badge {
display: inline-block;
background: #28a745;
color: white;
padding: 2px 12px;
border-radius: 20px;
font-size: 0.8em;
font-weight: bold;
}
.grid-2 {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
</style>
</head>
<body>
<h1>Microdata โ Structured Data</h1>
<!-- ====== SECTION 1: PERSON ====== -->
<h2>1. Person</h2>
<div class="demo-container">
<div class="microdata-example">
<h3>Rendered Content:</h3>
<div itemscope itemtype="https://schema.org/Person">
<p><strong>Name:</strong> <span itemprop="name">Kronos</span></p>
<p><strong>Job Title:</strong> <span itemprop="jobTitle">Fullstack Developer</span></p>
<p><strong>Email:</strong> <a href="mailto:johndoe@example.com" itemprop="email">johndoe@example.com</a></p>
<p><strong>Birth Date:</strong> <span itemprop="birthDate">1990-05-15</span></p>
<p><strong>Nationality:</strong> <span itemprop="nationality">American</span></p>
</div>
</div>
<div class="code-block">
<span style="color: #569cd6;"><div</span> <span style="color: #9cdcfe;">itemscope</span> <span style="color: #9cdcfe;">itemtype</span>=<span style="color: #ce9178;">"https://schema.org/Person"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <p><strong></span>Name:<span style="color: #569cd6;"></strong></span> <span style="color: #569cd6;"><span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"name"</span><span style="color: #569cd6;">></span>Kronos<span style="color: #569cd6;"></span></p></span>
<span style="color: #569cd6;"> <p><strong></span>Job Title:<span style="color: #569cd6;"></strong></span> <span style="color: #569cd6;"><span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"jobTitle"</span><span style="color: #569cd6;">></span>Fullstack Developer<span style="color: #569cd6;"></span></p></span>
<span style="color: #569cd6;"> <p><strong></span>Email:<span style="color: #569cd6;"></strong></span> <span style="color: #569cd6;"><a</span> <span style="color: #9cdcfe;">href</span>=<span style="color: #ce9178;">"mailto:johndoe@example.com"</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"email"</span><span style="color: #569cd6;">></span>johndoe@example.com<span style="color: #569cd6;"></a></p></span>
<span style="color: #569cd6;"> <p><strong></span>Birth Date:<span style="color: #569cd6;"></strong></span> <span style="color: #569cd6;"><span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"birthDate"</span><span style="color: #569cd6;">></span>1990-05-15<span style="color: #569cd6;"></span></p></span>
<span style="color: #569cd6;"> <p><strong></span>Nationality:<span style="color: #569cd6;"></strong></span> <span style="color: #569cd6;"><span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"nationality"</span><span style="color: #569cd6;">></span>American<span style="color: #569cd6;"></span></p></span>
<span style="color: #569cd6;"></div></span>
</div>
</div>
<!-- ====== SECTION 2: ORGANIZATION ====== -->
<h2>2. Organization</h2>
<div class="demo-container">
<div class="microdata-example">
<h3>Rendered Content:</h3>
<div itemscope itemtype="https://schema.org/Organization">
<p><strong>Organization:</strong> <span itemprop="name">TechCorp Inc.</span></p>
<p><strong>URL:</strong> <a href="https://techcorp.com" itemprop="url">https://techcorp.com</a></p>
<p><strong>Description:</strong> <span itemprop="description">A leading provider of innovative technology solutions.</span></p>
<div itemprop="address" itemscope itemtype="https://schema.org/PostalAddress">
<p><strong>Address:</strong></p>
<p itemprop="streetAddress">123 Tech Street</p>
<p itemprop="addressLocality">Silicon Valley</p>
<p itemprop="addressRegion">CA</p>
<p itemprop="postalCode">94043</p>
</div>
<p><strong>Phone:</strong> <span itemprop="telephone">(555) 123-4567</span></p>
</div>
</div>
<div class="code-block">
<span style="color: #569cd6;"><div</span> <span style="color: #9cdcfe;">itemscope</span> <span style="color: #9cdcfe;">itemtype</span>=<span style="color: #ce9178;">"https://schema.org/Organization"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <div</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"address"</span> <span style="color: #9cdcfe;">itemscope</span> <span style="color: #9cdcfe;">itemtype</span>=<span style="color: #ce9178;">"https://schema.org/PostalAddress"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"streetAddress"</span><span style="color: #569cd6;">></span>123 Tech Street<span style="color: #569cd6;"></span></span>
<span style="color: #569cd6;"> <span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"addressLocality"</span><span style="color: #569cd6;">></span>Silicon Valley<span style="color: #569cd6;"></span></span>
<span style="color: #569cd6;"> <span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"addressRegion"</span><span style="color: #569cd6;">></span>CA<span style="color: #569cd6;"></span></span>
<span style="color: #569cd6;"> <span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"postalCode"</span><span style="color: #569cd6;">></span>94043<span style="color: #569cd6;"></span></span>
<span style="color: #569cd6;"> </div></span>
<span style="color: #569cd6;"></div></span>
</div>
</div>
<!-- ====== SECTION 3: ARTICLE ====== -->
<h2>3. Article</h2>
<div class="demo-container">
<div class="microdata-example">
<h3>Rendered Content:</h3>
<div itemscope itemtype="https://schema.org/Article">
<h2 itemprop="headline">The Future of Web Development</h2>
<p><strong>Author:</strong> <span itemprop="author">John Doe</span></p>
<p><strong>Published:</strong> <time itemprop="datePublished" datetime="2024-01-15">January 15, 2024</time></p>
<p itemprop="description">An in-depth look at the emerging trends in web development.</p>
<div itemprop="articleBody">
<p>Web development is evolving rapidly. New frameworks, tools, and methodologies are emerging every year...</p>
</div>
<p><strong>Keywords:</strong> <span itemprop="keywords">HTML, CSS, JavaScript, Web Development</span></p>
</div>
</div>
<div class="code-block">
<span style="color: #569cd6;"><div</span> <span style="color: #9cdcfe;">itemscope</span> <span style="color: #9cdcfe;">itemtype</span>=<span style="color: #ce9178;">"https://schema.org/Article"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <h2</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"headline"</span><span style="color: #569cd6;">></span>The Future of Web Development<span style="color: #569cd6;"></h2></span>
<span style="color: #569cd6;"> <p><strong></span>Author:<span style="color: #569cd6;"></strong></span> <span style="color: #569cd6;"><span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"author"</span><span style="color: #569cd6;">></span>John Doe<span style="color: #569cd6;"></span></p></span>
<span style="color: #569cd6;"> <time</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"datePublished"</span> <span style="color: #9cdcfe;">datetime</span>=<span style="color: #ce9178;">"2024-01-15"</span><span style="color: #569cd6;">></span>January 15, 2024<span style="color: #569cd6;"></time></span>
<span style="color: #569cd6;"> <div</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"articleBody"</span><span style="color: #569cd6;">></span>...<span style="color: #569cd6;"></div></span>
<span style="color: #569cd6;"></div></span>
</div>
</div>
<!-- ====== SECTION 4: PRODUCT ====== -->
<h2>4. Product with Offer</h2>
<div class="demo-container">
<div class="microdata-example">
<h3>Rendered Content:</h3>
<div itemscope itemtype="https://schema.org/Product">
<img src="https://via.placeholder.com/150x150/007bff/ffffff?text=Product" itemprop="image" alt="Product Image">
<h2 itemprop="name">Wireless Bluetooth Headphones</h2>
<p itemprop="description">Premium wireless headphones with noise cancellation and 20-hour battery life.</p>
<p><strong>SKU:</strong> <span itemprop="sku">WH-1000X</span></p>
<div itemprop="offers" itemscope itemtype="https://schema.org/Offer">
<p><strong>Price:</strong> <span itemprop="price">199.99</span> <span itemprop="priceCurrency">USD</span></p>
<p><strong>Availability:</strong> <link itemprop="availability" href="https://schema.org/InStock">In Stock</p>
</div>
<div itemprop="aggregateRating" itemscope itemtype="https://schema.org/AggregateRating">
<p><strong>Rating:</strong> <span itemprop="ratingValue">4.5</span> / 5 (<span itemprop="reviewCount">127</span> reviews)</p>
</div>
</div>
</div>
<div class="code-block">
<span style="color: #569cd6;"><div</span> <span style="color: #9cdcfe;">itemscope</span> <span style="color: #9cdcfe;">itemtype</span>=<span style="color: #ce9178;">"https://schema.org/Product"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <div</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"offers"</span> <span style="color: #9cdcfe;">itemscope</span> <span style="color: #9cdcfe;">itemtype</span>=<span style="color: #ce9178;">"https://schema.org/Offer"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"price"</span><span style="color: #569cd6;">></span>199.99<span style="color: #569cd6;"></span></span>
<span style="color: #569cd6;"> <span</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"priceCurrency"</span><span style="color: #569cd6;">></span>USD<span style="color: #569cd6;"></span></span>
<span style="color: #569cd6;"> <link</span> <span style="color: #9cdcfe;">itemprop</span>=<span style="color: #ce9178;">"availability"</span> <span style="color: #9cdcfe;">href</span>=<span style="color: #ce9178;">"https://schema.org/InStock"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> </div></span>
<span style="color: #569cd6;"></div></span>
</div>
</div>
<!-- ====== SECTION 5: RECIPE ====== -->
<h2>5. Recipe</h2>
<div class="demo-container">
<div class="microdata-example">
<h3>Rendered Content:</h3>
<div itemscope itemtype="https://schema.org/Recipe">
<h2 itemprop="name">Classic Chocolate Chip Cookies</h2>
<p><strong>Author:</strong> <span itemprop="author">Sarah Baker</span></p>
<p><strong>Prep Time:</strong> <span itemprop="prepTime">PT15M</span> (15 minutes)</p>
<p><strong>Cook Time:</strong> <span itemprop="cookTime">PT10M</span> (10 minutes)</p>
<p><strong>Yield:</strong> <span itemprop="recipeYield">24 cookies</span></p>
<p><strong>Ingredients:</strong></p>
<ul>
<li itemprop="recipeIngredient">2 1/4 cups all-purpose flour</li>
<li itemprop="recipeIngredient">1 tsp baking soda</li>
<li itemprop="recipeIngredient">1 cup unsalted butter, softened</li>
<li itemprop="recipeIngredient">3/4 cup granulated sugar</li>
<li itemprop="recipeIngredient">2 cups chocolate chips</li>
</ul>
<p><strong>Instructions:</strong></p>
<ol>
<li itemprop="recipeInstructions">Preheat oven to 375ยฐF.</li>
<li itemprop="recipeInstructions">Mix flour and baking soda together.</li>
<li itemprop="recipeInstructions">Cream butter and sugars until smooth.</li>
<li itemprop="recipeInstructions">Add eggs and vanilla.</li>
<li itemprop="recipeInstructions">Gradually add dry ingredients.</li>
<li itemprop="recipeInstructions">Stir in chocolate chips.</li>
<li itemprop="recipeInstructions">Drop spoonfuls onto baking sheets.</li>
<li itemprop="recipeInstructions">Bake for 10-12 minutes.</li>
</ol>
</div>
</div>
</div>
<!-- ====== SECTION 6: EVENT ====== -->
<h2>6. Event</h2>
<div class="demo-container">
<div class="microdata-example">
<h3>Rendered Content:</h3>
<div itemscope itemtype="https://schema.org/Event">
<h2 itemprop="name">Tech Conference 2025</h2>
<p><strong>Description:</strong> <span itemprop="description">The largest technology conference in the region.</span></p>
<p><strong>Start Date:</strong> <time itemprop="startDate" datetime="2025-05-15T09:00">May 15, 2025 9:00 AM</time></p>
<p><strong>End Date:</strong> <time itemprop="endDate" datetime="2025-05-17T18:00">May 17, 2025 6:00 PM</time></p>
<div itemprop="location" itemscope itemtype="https://schema.org/Place">
<p><strong>Location:</strong> <span itemprop="name">Convention Center</span></p>
<div itemprop="address" itemscope itemtype="https://schema.org/PostalAddress">
<p itemprop="streetAddress">123 Main Street</p>
<p itemprop="addressLocality">San Francisco</p>
<p itemprop="addressRegion">CA</p>
<p itemprop="postalCode">94105</p>
</div>
</div>
<div itemprop="offers" itemscope itemtype="https://schema.org/Offer">
<p><strong>Price:</strong> <span itemprop="price">299.00</span> <span itemprop="priceCurrency">USD</span></p>
</div>
<p><strong>Performer:</strong> <span itemprop="performer">Keynote Speakers</span></p>
</div>
</div>
</div>
<!-- ====== SECTION 7: REVIEW ====== -->
<h2>7. Review</h2>
<div class="demo-container">
<div class="microdata-example">
<h3>Rendered Content:</h3>
<div itemscope itemtype="https://schema.org/Review">
<div itemprop="itemReviewed" itemscope itemtype="https://schema.org/Product">
<h3 itemprop="name">Wireless Bluetooth Headphones</h3>
</div>
<p><strong>Rating:</strong></p>
<div itemprop="reviewRating" itemscope itemtype="https://schema.org/Rating">
<span itemprop="ratingValue">4.5</span> / 5 stars
</div>
<p><strong>Review:</strong> <span itemprop="reviewBody">Excellent sound quality and comfortable to wear for long periods.</span></p>
<p><strong>Author:</strong> <span itemprop="author">John Doe</span></p>
<p><strong>Published:</strong> <time itemprop="datePublished" datetime="2024-02-10">February 10, 2024</time></p>
</div>
</div>
</div>
<!-- ====== SECTION 8: REFERENCE TABLES ====== -->
<h2>8. Quick Reference</h2>
<h3>Microdata Attributes</h3>
<table class="reference-table">
<thead>
<tr>
<th>Attribute</th>
<th>Purpose</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>itemscope</code></td>
<td>Creates a new item</td>
<td><code>itemscope</code></td>
</tr>
<tr>
<td><code>itemtype</code></td>
<td>Specifies the item type (schema.org URL)</td>
<td><code>itemtype="https://schema.org/Person"</code></td>
</tr>
<tr>
<td><code>itemprop</code></td>
<td>Specifies a property of the item</td>
<td><code>itemprop="name"</code></td>
</tr>
</tbody>
</table>
<h3>Common Schema.org Types</h3>
<table class="reference-table">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
<th>Common Properties</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Person</code></td>
<td>A person</td>
<td><code>name</code>, <code>jobTitle</code>, <code>email</code>, <code>address</code></td>
</tr>
<tr>
<td><code>Organization</code></td>
<td>An organization</td>
<td><code>name</code>, <code>url</code>, <code>address</code>, <code>logo</code></td>
</tr>
<tr>
<td><code>Article</code></td>
<td>A news article</td>
<td><code>headline</code>, <code>author</code>, <code>datePublished</code></td>
</tr>
<tr>
<td><code>Product</code></td>
<td>A product</td>
<td><code>name</code>, <code>offers</code>, <code>aggregateRating</code></td>
</tr>
<tr>
<td><code>Recipe</code></td>
<td>A recipe</td>
<td><code>name</code>, <code>recipeIngredient</code>, <code>recipeInstructions</code></td>
</tr>
<tr>
<td><code>Event</code></td>
<td>An event</td>
<td><code>name</code>, <code>startDate</code>, <code>location</code>, <code>offers</code></td>
</tr>
<tr>
<td><code>Place</code></td>
<td>A place</td>
<td><code>name</code>, <code>address</code>, <code>geo</code></td>
</tr>
</tbody>
</table>
<!-- ====== SECTION 9: BEST PRACTICES ====== -->
<h2>9. Best Practices</h2>
<div style="background: #d4edda; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745;">
<h3 style="margin-top: 0; color: #155724;">โ
Do This:</h3>
<ul>
<li>Use <strong>schema.org</strong> vocabulary โ the most widely supported</li>
<li>Add structured data to <strong>all pages</strong> where applicable</li>
<li>Use <strong>nested items</strong> for complex data (e.g., address inside a person)</li>
<li>Use <strong>appropriate data types</strong> (e.g., <code>datetime</code> for dates)</li>
<li>Test your structured data with <strong>Google's Rich Results Test</strong></li>
<li>Keep your microdata <strong>up-to-date</strong> with page content</li>
</ul>
</div>
<div style="background: #f8d7da; padding: 20px; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 15px;">
<h3 style="margin-top: 0; color: #721c24;">โ Don't Do This:</h3>
<ul>
<li>Don't use <strong>irrelevant</strong> schema types</li>
<li>Don't add <strong>hidden</strong> or invisible structured data</li>
<li>Don't use <strong>inconsistent</strong> data (e.g., mismatched prices)</li>
<li>Don't forget to <strong>validate</strong> your microdata</li>
<li>Don't use <strong>outdated</strong> schema.org versions</li>
</ul>
</div>
<!-- ====== SECTION 10: OTHER FORMATS ====== -->
<h2>10. Other Structured Data Formats</h2>
<div class="grid-2">
<div style="background: white; padding: 20px; border-radius: 8px; border: 2px solid #ddd;">
<h3>๐ JSON-LD</h3>
<p>JSON-LD (JavaScript Object Notation for Linked Data) is the <strong>recommended</strong> format by Google.</p>
<div class="code-block" style="font-size: 0.8em;">
<span style="color: #569cd6;">{</span>
<span style="color: #569cd6;"> "@context":</span> <span style="color: #ce9178;">"https://schema.org"</span>,
<span style="color: #569cd6;"> "@type":</span> <span style="color: #ce9178;">"Person"</span>,
<span style="color: #569cd6;"> "name":</span> <span style="color: #ce9178;">"John Doe"</span>,
<span style="color: #569cd6;"> "jobTitle":</span> <span style="color: #ce9178;">"Developer"</span>
<span style="color: #569cd6;">}</span>
</div>
</div>
<div style="background: white; padding: 20px; border-radius: 8px; border: 2px solid #ddd;">
<h3>๐งฉ RDFa</h3>
<p>RDFa (Resource Description Framework in Attributes) is another way to add structured data.</p>
<div class="code-block" style="font-size: 0.8em;">
<span style="color: #569cd6;"><div</span> <span style="color: #9cdcfe;">vocab</span>=<span style="color: #ce9178;">"https://schema.org/"</span> <span style="color: #9cdcfe;">typeof</span>=<span style="color: #ce9178;">"Person"</span><span style="color: #569cd6;">></span>
<span style="color: #569cd6;"> <span</span> <span style="color: #9cdcfe;">property</span>=<span style="color: #ce9178;">"name"</span><span style="color: #569cd6;">></span>John Doe<span style="color: #569cd6;"></span></span>
<span style="color: #569cd6;"></div></span>
</div>
</div>
</div>
</body>
</html>
Quick Reference
| Attribute | Purpose | Example |
|---|---|---|
itemscope | Creates a new item | itemscope |
itemtype | Specifies the item type | itemtype="https://schema.org/Person" |
itemprop | Specifies a property | itemprop="name" |
Common Schema.org Types
| Type | Description | Example Properties |
|---|---|---|
Person | A person | name, jobTitle, email, address, birthDate |
Organization | An organization | name, url, address, logo, telephone |
Article | A news article | headline, author, datePublished, articleBody |
Product | A product | name, offers, aggregateRating, image |
Recipe | A recipe | name, recipeIngredient, recipeInstructions, cookTime |
Event | An event | name, startDate, location, offers |
Review | A review | reviewRating, reviewBody, author |
Place | A place | name, address, geo |
Best Practices Checklist
- โ Use schema.org vocabulary
- โ Add structured data to all relevant pages
- โ Use nested items for complex data
- โ Use appropriate data types (datetime, etc.)
- โ Test with Google’s Rich Results Test
- โ Keep data up-to-date with page content
- โ Use JSON-LD for better compatibility (Google’s recommended format)
Pro Tip: Microdata is a powerful tool for improving your website’s SEO. Using schema.org vocabulary helps search engines display rich snippets โ enhanced search results with images, ratings, prices, and more. Always validate your structured data and keep it consistent with your page content!
HTML Cheatsheet
1. Basic HTML Document Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page description for SEO">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="Your Name">
<title>Page Title</title>
<link rel="stylesheet" href="styles.css">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<style>
/* Internal CSS */
</style>
</head>
<body>
<!-- Content goes here -->
<script src="script.js"></script>
</body>
</html>
Document Structure Elements
| Element | Description |
|---|---|
<!DOCTYPE html> | Declares HTML5 document type |
<html> | Root element |
<head> | Contains metadata |
<title> | Page title (browser tab) |
<meta> | Metadata (charset, viewport, SEO) |
<link> | External resources (CSS, favicon) |
<style> | Internal CSS |
<script> | JavaScript |
<body> | Visible content |
2. Headings
<h1>Heading 1 โ Most Important</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6 โ Least Important</h6>
Best Practices:
- Use only one
<h1>per page - Don’t skip levels (h1 โ h2 โ h3)
- Don’t use headings just to make text bigger
3. Text Content
Paragraphs
<p>This is a paragraph of text.</p>
Text Formatting
| Element | Description | Example |
|---|---|---|
<strong> | Strong importance (bold) | <strong>Important</strong> |
<b> | Bold (no semantic meaning) | <b>Bold</b> |
<em> | Emphasized (italic) | <em>Emphasis</em> |
<i> | Italic (no semantic meaning) | <i>Italic</i> |
<u> | Underline | <u>Underlined</u> |
<mark> | Highlighted | <mark>Highlighted</mark> |
<ins> | Inserted text | <ins>Inserted</ins> |
<del> | Deleted text | <del>Deleted</del> |
<small> | Smaller text | <small>Small</small> |
<sub> | Subscript | H<sub>2</sub>O |
<sup> | Superscript | E = mc<sup>2</sup> |
<code> | Inline code | <code>print()</code> |
<kbd> | Keyboard input | <kbd>Ctrl</kbd> + <kbd>S</kbd> |
<samp> | Sample output | <samp>Error!</samp> |
<var> | Variable | <var>x</var> = 5 |
<abbr> | Abbreviation | <abbr title="HyperText Markup Language">HTML</abbr> |
<q> | Inline quote | <q>To be or not to be</q> |
<cite> | Citation | <cite>Book Title</cite> |
<blockquote> | Block quote | <blockquote>Quote</blockquote> |
<pre> | Preformatted text | <pre> spaces preserved</pre> |
<br> | Line break | Line 1<br>Line 2 |
<hr> | Horizontal rule | <hr> |
<p>This is <strong>bold</strong> and <em>italic</em> text.</p>
<p>Water is H<sub>2</sub>O and E = mc<sup>2</sup>.</p>
<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy.</p>
<pre>
This text preserves
spaces and line breaks.
</pre>
4. Links
<!-- External link -->
<a href="https://www.example.com">Visit Example</a>
<!-- Open in new tab -->
<a href="https://www.example.com" target="_blank" rel="noopener noreferrer">New Tab</a>
<!-- Email link -->
<a href="mailto:info@example.com">Send Email</a>
<!-- Phone link -->
<a href="tel:+1234567890">Call Us</a>
<!-- Internal link (same page) -->
<a href="#section-id">Jump to Section</a>
<!-- Download link -->
<a href="file.pdf" download>Download PDF</a>
| Attribute | Description |
|---|---|
href | Destination URL |
target | _self (default), _blank, _parent, _top |
rel | Relationship (noopener noreferrer for external) |
download | Downloads instead of navigating |
title | Tooltip text |
5. Images
<!-- Basic image -->
<img src="image.jpg" alt="Description of image">
<!-- With dimensions -->
<img src="image.jpg" alt="Description" width="300" height="200">
<!-- Responsive image -->
<img src="image.jpg" alt="Description" style="max-width: 100%; height: auto;">
<!-- Responsive with picture -->
<picture>
<source srcset="image-mobile.jpg" media="(max-width: 768px)">
<source srcset="image-desktop.jpg" media="(min-width: 769px)">
<img src="image-default.jpg" alt="Description">
</picture>
| Attribute | Description |
|---|---|
src | Image URL |
alt | Alternative text (required for accessibility) |
width / height | Dimensions |
loading | lazy for lazy loading |
srcset | Multiple image sources for responsive |
6. Lists
Unordered List (Bullets)
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3
<ul>
<li>Nested item</li>
</ul>
</li>
</ul>
Ordered List (Numbers)
<ol>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ol>
<!-- With type attribute -->
<ol type="A"> <!-- A, B, C -->
<ol type="a"> <!-- a, b, c -->
<ol type="I"> <!-- I, II, III -->
<ol type="i"> <!-- i, ii, iii -->
<ol type="1"> <!-- 1, 2, 3 (default) -->
<!-- With start attribute -->
<ol start="5">
<li>Item 5</li>
<li>Item 6</li>
</ol>
Description List
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets</dd>
</dl>
7. Divisions and Spans
<!-- Block-level container -->
<div class="container">
<h2>Section Title</h2>
<p>Content</p>
</div>
<!-- Inline container -->
<p>This is <span style="color: red;">highlighted</span> text.</p>
| Element | Display | Use |
|---|---|---|
<div> | Block | Grouping content, layout |
<span> | Inline | Styling part of text |
8. Tables
<table>
<caption>Product List</caption>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Stock</th>
</tr>
</thead>
<tbody>
<tr>
<td>Product A</td>
<td>$10.99</td>
<td>45</td>
</tr>
<tr>
<td>Product B</td>
<td>$25.49</td>
<td>18</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Total</td>
<td>63</td>
</tr>
</tfoot>
</table>
| Element | Description |
|---|---|
<table> | Table container |
<caption> | Table title |
<thead> | Header section |
<tbody> | Body section |
<tfoot> | Footer section |
<tr> | Table row |
<th> | Header cell |
<td> | Data cell |
colspan | Merge columns |
rowspan | Merge rows |
9. Forms
Complete Form Example
<form action="/submit" method="post">
<!-- Text Input -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Your name" required>
<!-- Email Input -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<!-- Password Input -->
<label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="8">
<!-- Number Input -->
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="1" max="120">
<!-- Date Input -->
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">
<!-- Radio Buttons -->
<fieldset>
<legend>Gender:</legend>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
</fieldset>
<!-- Checkboxes -->
<fieldset>
<legend>Interests:</legend>
<input type="checkbox" id="html" name="interests" value="html">
<label for="html">HTML</label>
<input type="checkbox" id="css" name="interests" value="css">
<label for="css">CSS</label>
</fieldset>
<!-- Select Dropdown -->
<label for="country">Country:</label>
<select id="country" name="country">
<optgroup label="Europe">
<option value="uk">United Kingdom</option>
<option value="de">Germany</option>
</optgroup>
<optgroup label="Americas">
<option value="us">United States</option>
<option value="ca">Canada</option>
</optgroup>
</select>
<!-- Textarea -->
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"></textarea>
<!-- File Upload -->
<label for="file">Upload File:</label>
<input type="file" id="file" name="file">
<!-- Range Slider -->
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100" value="50">
<!-- Hidden Input -->
<input type="hidden" name="token" value="abc123">
<!-- Buttons -->
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<button type="button" onclick="alert('Clicked!')">Click Me</button>
</form>
Form Attributes
| Attribute | Description |
|---|---|
action | URL to submit to |
method | get or post |
enctype | multipart/form-data for file uploads |
target | Where to display response |
autocomplete | on or off |
novalidate | Disable browser validation |
Input Types
| Type | Description |
|---|---|
text | Single-line text |
email | Email (with validation) |
password | Hidden characters |
number | Numeric input |
tel | Phone number |
url | URL (with validation) |
date | Date picker |
time | Time picker |
datetime-local | Date + time |
range | Slider |
color | Color picker |
file | File upload |
checkbox | Toggle |
radio | Single selection |
hidden | Invisible data |
submit | Submit button |
reset | Reset button |
10. Semantic HTML5 Elements
<header>
<h1>Website Header</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<section>
<h2>Section Title</h2>
<article>
<h3>Article Heading</h3>
<p>Article content...</p>
</article>
</section>
<aside>
<h3>Related Links</h3>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</aside>
</main>
<footer>
<p>ยฉ 2024 My Website</p>
</footer>
<details>
<summary>Click to expand</summary>
<p>Hidden content...</p>
</details>
| Element | Description |
|---|---|
<header> | Introductory content |
<nav> | Navigation links |
<main> | Main content (one per page) |
<section> | Thematic grouping |
<article> | Self-contained content |
<aside> | Sidebar / supplementary |
<footer> | Footer content |
<details> | Expandable content |
<summary> | Heading for <details> |
<figure> | Image with caption |
<figcaption> | Caption for <figure> |
<time> | Date/time |
<mark> | Highlighted text |
11. Multimedia
Audio
<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>
Video
<video width="320" height="240" controls poster="thumbnail.jpg" muted loop>
<source src="movie.mp4" type="video/mp4">
<source src="movie.webm" type="video/webm">
Your browser does not support the video tag.
</video>
| Attribute | Description |
|---|---|
controls | Show playback controls |
autoplay | Auto-play (requires muted) |
muted | Start muted |
loop | Repeat |
poster | Thumbnail image |
preload | auto, metadata, none |
Iframes
<iframe src="https://www.example.com"
width="500"
height="300"
title="Embedded Content"
allowfullscreen>
</iframe>
Embed & Object
<embed src="file.pdf" type="application/pdf" width="500" height="300">
<object data="file.pdf" type="application/pdf" width="500" height="300">
<p>Fallback content</p>
</object>
12. SVG (Scalable Vector Graphics)
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- Circle -->
<circle cx="100" cy="100" r="80" fill="blue" stroke="black" stroke-width="2"/>
<!-- Rectangle -->
<rect x="20" y="20" width="100" height="60" fill="red" rx="10"/>
<!-- Line -->
<line x1="0" y1="0" x2="200" y2="200" stroke="green" stroke-width="2"/>
<!-- Polygon -->
<polygon points="100,10 40,180 190,60 10,60 160,180" fill="purple"/>
<!-- Path -->
<path d="M 10 10 L 90 90" stroke="blue" stroke-width="2" fill="none"/>
<!-- Text -->
<text x="100" y="100" text-anchor="middle" fill="white">SVG</text>
</svg>
| Element | Description |
|---|---|
<svg> | SVG container |
<circle> | Circle (cx, cy, r) |
<rect> | Rectangle (x, y, width, height, rx, ry) |
<ellipse> | Ellipse (cx, cy, rx, ry) |
<line> | Line (x1, y1, x2, y2) |
<polygon> | Polygon (points) |
<polyline> | Polyline (points) |
<path> | Complex path (d) |
<text> | Text |
13. Attributes
Global Attributes
| Attribute | Description | Example |
|---|---|---|
id | Unique identifier | id="header" |
class | Class name(s) | class="btn primary" |
style | Inline CSS | style="color: red;" |
title | Tooltip text | title="Click me" |
data-* | Custom data | data-user-id="123" |
hidden | Hide element | hidden |
lang | Language | lang="en" |
dir | Text direction | dir="rtl" |
tabindex | Tab order | tabindex="1" |
contenteditable | Editable | contenteditable="true" |
draggable | Draggable | draggable="true" |
Data Attributes
<div data-user-id="123" data-role="admin" data-theme="dark">
Content
</div>
<!-- Access with JavaScript -->
<script>
const el = document.querySelector('div');
console.log(el.dataset.userId); // "123"
console.log(el.dataset.role); // "admin"
</script>
14. Other Useful Elements
<!-- Horizontal Rule -->
<hr>
<!-- Line Break -->
<br>
<!-- Button -->
<button type="button">Click Me</button>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<!-- Progress -->
<progress value="70" max="100">70%</progress>
<!-- Meter -->
<meter value="0.6" min="0" max="1">60%</meter>
<!-- Time -->
<time datetime="2024-01-15T14:00">January 15, 2024 at 2 PM</time>
<!-- Details / Summary -->
<details>
<summary>Click to expand</summary>
<p>Hidden content</p>
</details>
<!-- Figure / Figcaption -->
<figure>
<img src="image.jpg" alt="Description">
<figcaption>Figure 1: Description</figcaption>
</figure>
<!-- Address -->
<address>
<a href="mailto:info@example.com">info@example.com</a><br>
123 Main Street, City
</address>
<!-- Code Block -->
<pre><code>
function hello() {
console.log("Hello, World!");
}
</code></pre>
15. Comments
<!-- This is a single-line comment -->
<!--
This is a
multi-line comment
-->
<!-- Comments can be used to temporarily disable code -->
<!-- <p>This won't be displayed</p> -->
16. Best Practices
โ Do This
<!-- Always include DOCTYPE -->
<!DOCTYPE html>
<!-- Always set lang attribute -->
<html lang="en">
<!-- Always include viewport meta tag -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Always include alt text for images -->
<img src="photo.jpg" alt="Description of photo">
<!-- Use semantic elements -->
<header>, <nav>, <main>, <article>, <footer>
<!-- Use labels with form inputs -->
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<!-- Use lowercase for tags and attributes -->
<div class="container">
<!-- Close all elements properly -->
<p>Content</p>
<!-- Use meaningful class names -->
<div class="product-card">
โ Don’t Do This
<!-- Don't skip DOCTYPE -->
<html>
<!-- Don't forget lang attribute -->
<html>
<!-- Don't use images without alt -->
<img src="photo.jpg">
<!-- Don't use div for everything -->
<div class="header">, <div class="nav">
<!-- Don't use inline styles for everything -->
<p style="color: red; font-size: 16px; margin: 10px;">
<!-- Don't use tables for layout -->
<table><tr><td>Header</td></tr></table>
<!-- Don't use <br> for spacing -->
<br><br><br>
<!-- Don't use outdated elements -->
<center>, <font>, <marquee>
Quick Reference Card
DOCUMENT STRUCTURE TEXT FORMATTING FORMS
โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโ
<!DOCTYPE html> <strong> Bold <form>
<html> <em> Italic <input>
<head> <mark> Highlight <label>
<title> <del> Deleted <select>
<meta> <ins> Inserted <option>
<body> <sub>/<sup> Sub/Super <textarea>
<code> Code <button>
HEADINGS <pre> Preformatted <fieldset>
โโโโโโโโ <blockquote> Quote <legend>
<h1> through <h6> <abbr> Abbreviation
<cite> Citation TABLES
LISTS โโโโโโ
โโโโโ LINKS <table>
<ul> Unordered โโโโโ <thead>/<tbody>/<tfoot>
<ol> Ordered <a href="url"> <tr> Row
<li> List item <a href="mailto:"> <th> Header
<dl> Description <a href="tel:"> <td> Data
<dt> Term <a target="_blank"> <caption>
<dd> Definition colspan/rowspan
IMAGES SEMANTIC ELEMENTS MULTIMEDIA
โโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโโโ
<img src="" alt=""> <header> <audio>
<picture> <nav> <video>
<source> <main> <iframe>
<figure> <section> <embed>
<figcaption> <article> <object>
<aside>
DIV/SPAN <footer> SVG
โโโโโโโโ <details> โโโ
<div> Block <summary> <svg>
<span> Inline <time> <circle>/<rect>
<figure> <line>/<polygon>
<path>/<text>
THE END
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!