HTML Refresher
Chapter 1: Introduction to HTML
1.1 What is HTML? (HyperText Markup Language)
Explanation: HTML stands for HyperText Markup Language. It’s the standard markup language for creating web pages. It’s not a programming language; it’s a markup language. This means it uses tags to structure the content of a web page, telling the browser how to display text, images, links, and other elements.
Key Terms:
- HyperText: Text that contains links to other text. Think of clicking a word or phrase on a webpage and being taken to a different page or a different section of the same page.
<a href="https://www.google.com">Google</a>
- Markup Language: A language that uses tags to define the structure and content of a document.
<h1> Linear Algebra book </h1>
<h2> Chapter #1: Linear Equation </h2>
<p>
Linear equation is used to solve variable for the given relationships to different variables.
</p>
<h2> Chapter #2: Multi variable linear equation>
<p>
Multiple variables in the input.
</p>
- Web Page: A document displayed in a web browser.
<html>
<title> Linear Algebra book</title>
<body>
<h1> Linear Algebra book </h1>
<h2> Chapter #1: Linear Equation </h2>
<p>
Linear equation is used to solve variable for the given relationships to different variables.
</p>
<h2> Chapter #2: Multi variable linear equation>
<p>
Multiple variables in the input.
</p>
</body>
</html>
- Website: A collection of related web pages.
https://www.ndtv.com
- Analogy: Think of HTML as the skeleton of a house. It provides the structure and defines where the walls, doors, windows, and roof go. CSS (Cascading Style Sheets) is the paint, furniture, and decorations that make the house look good. JavaScript is the electrical wiring, plumbing, and appliances that make the house functional.
1.2 History of HTML
Explanation: HTML was invented by Tim Berners-Lee in 1990 while working at CERN. He needed a way for scientists to easily share documents and information. The first version was very simple, but it has evolved significantly over the years. The World Wide Web Consortium (W3C) is now the main organization responsible for developing and maintaining HTML standards.
Key Milestones:
- 1990: Tim Berners-Lee invents HTML.
- 1995: HTML 2.0 is the first standard specification.
- 1997: HTML 3.2 adds support for more features.
- 1999: HTML 4.01 is widely adopted.
- 2014: HTML5 is finalized, introducing many new features and semantic elements. This is the current standard.
- Why it matters: Understanding the history helps you appreciate why certain features exist and how the language has evolved to meet the changing needs of the web.
1.3 HTML Structure: Elements, Tags, and Attributes
Explanation: This is fundamental. HTML is built upon elements, which are defined by tags, and can be modified using attributes.
Element: A part of the web page’s structure. For example, a paragraph, a heading, an image, a link, etc. An element typically consists of a start tag, some content, and an end tag.
<a href="https://www.google.com">Google</a>
<img src="https://upload.wikimedia.org/wikipedia/commons/archive/c/c1/20200429221626%21Google_%22G%22_logo.svg"/>
Tag: A keyword enclosed in angle brackets (< and >). Tags are used to define the start and end of an HTML element. Most tags come in pairs: a start tag (<p>) and an end tag (</p>). End tags have a forward slash (/) before the element name.
<p> Text value </p>
Attribute: Provides additional information about an HTML element. Attributes are specified within the start tag and usually consist of a name and a value, separated by an equals sign (=). The value is enclosed in quotes (single or double).
Example:
<p id="my-paragraph" class="important-text">This is a paragraph of text.</p>
- <p> is the start tag for the paragraph element.
- </p> is the end tag for the paragraph element.
- This is a paragraph of text. is the content of the paragraph element.
- id=”my-paragraph” is an attribute that assigns the ID “my-paragraph” to the paragraph. This is useful for styling with CSS or manipulating with JavaScript.
- class=”important-text” is an attribute that assigns the class “important-text” to the paragraph. Classes are also used for styling and JavaScript.
Self-Closing Tags: Some elements don’t have content and are therefore self-closing. In HTML5, you don’t need to close them, but it’s good practice. In XHTML they must be closed.
Examples:
<br>
<hr>
<img>
<input>
To self-close in XHTML/HTML5 syntax, you add a / before the closing bracket:
<br/>
<hr/>
<img/>
<input/>
1.4 HTML Document Structure: <!DOCTYPE html>, <html>, <head>, <body>
Explanation: Every HTML page follows a specific structure:
<!DOCTYPE html>: This declaration tells the browser that the document is an HTML5 document. It must be the very first thing in your HTML file. It’s not an HTML tag; it’s an instruction to the browser.
<html>: This is the root element of the HTML page. All other HTML elements must be nested within this tag.
<head>: This section contains meta-information about the HTML document, such as the title, character set, links to CSS stylesheets, and scripts. The content within the <head> is not displayed on the web page itself.
<body>: This section contains the visible page content, such as text, images, links, forms, and other media.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Web Page</title>
<link rel="stylesheet" href="style.css"> <!-- Link to an external stylesheet -->
</head>
<body>
<h1>Welcome to My Web Page!</h1>
<p>This is the main content of my page.</p>
</body>
</html>
lang=”en”: This attribute within the <html> tag specifies the language of the page (English). This is important for accessibility and search engines.
<meta charset=”UTF-8">: Specifies the character encoding for the document. UTF-8 is the most common and recommended encoding, as it supports a wide range of characters.
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">: This is crucial for responsive design. It tells the browser how to scale the page on different devices (mobile, tablet, desktop).
<title>My First Web Page</title>: Sets the title of the browser tab or window.
<link rel=”stylesheet” href=”style.css”>: Links an external CSS stylesheet to the HTML document. This allows you to style the page’s appearance.
1.5 Basic HTML Tags: <p>, <h1> to <h6>, <a>, <img>, <br>, <hr>
Explanation: These are some of the most commonly used HTML tags.
<p> (Paragraph): Defines a paragraph of text. Browsers automatically add a blank line before and after a paragraph.
<p>This is the first paragraph.</p> <p>This is the second paragraph.</p>
<h1> to <h6> (Headings): Define headings of different levels. <h1> is the most important (largest) heading, and <h6> is the least important (smallest). Use them in a hierarchical order.
<h1>This is a main heading</h1>
<h2>This is a subheading</h2>
<h3>This is a sub-subheading</h3>
- <a> (Anchor/Link): Creates a hyperlink to another web page, file, location in the same page, or email address. The href attribute specifies the destination of the link.
<a href="https://www.example.com">Visit Example Website</a> <a href="me@example.com">Email Me</a>
<img> (Image): Embeds an image in the page. The src attribute specifies the URL of the image, and the alt attribute provides alternative text if the image cannot be displayed.
<img src="image.jpg" alt="A beautiful landscape" width="500" height="300">
- <br> (Line Break): Inserts a single line break. It’s a self-closing tag. Use sparingly; CSS is often better for controlling spacing.
This is the first line.<br> This is the second line.
- <hr> (Horizontal Rule): Creates a horizontal line, visually separating sections of content. It’s a self-closing tag.
<p>This is above the line.</p> <hr> <p>This is below the line.</p>
1.6 Creating Your First HTML Page
Steps:
- Open a text editor: (e.g., Notepad, TextEdit, VS Code, Sublime Text).
- Type the HTML code: Start with the 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">
<title>My First Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is my first HTML page.</p>
</body>
</html>
3. Save the file: Save the file with a .html extension (e.g., index.html). Make sure to choose “All Files” as the save type (in Notepad) so it doesn’t save as a .txt file.
4. Open in a browser: Double-click the index.html file to open it in your web browser (Chrome, Firefox, Safari, Edge). You should see “Hello, World!” as a heading and “This is my first HTML page.” as a paragraph.
1.7 Viewing HTML Source Code
Explanation: Every web browser allows you to view the HTML source code of any web page. This is a great way to learn how other websites are structured.
How to view the source code:
- Chrome: Right-click on the page and select “View Page Source” or “Inspect”.
- Firefox: Right-click on the page and select “View Page Source” or “Inspect”.
- Safari: Right-click on the page and select “Show Page Source” or “Inspect Element”. (You may need to enable the “Develop” menu in Safari preferences.)
- Edge: Right-click on the page and select “View Page Source” or “Inspect”.
- “View Page Source” will show you the HTML as it was originally written.
- “Inspect” (or “Inspect Element”) opens the browser’s developer tools, which allows you to see the live HTML (which may be modified by JavaScript) and also lets you inspect the CSS styles applied to each element. The “Elements” tab in the Developer Tools is where you’ll see the HTML.
1.8 Online editor
You can also use online editor. For example use https://www.programiz.com/html/online-compiler/
Chapter 2: Text Formatting and Structure
2.1 Text Formatting Tags: <b>, <strong>, <i>, <em>, <mark>, <small>, <del>, <ins>, <sub>, <sup>
Explanation: These tags are used to apply different formatting styles to text within an HTML document. It’s crucial to understand both the visual effect and the semantic meaning (if any) that these tags convey.
- <b> (Bold): Makes text bold. Visually emphasizes the text, but has no semantic meaning.
- <strong> (Strong): Makes text bold. Semantically represents important text. Screen readers will often read strong text with more emphasis.
- <i> (Italic): Makes text italic. Visually emphasizes the text, but has no semantic meaning.
- <em> (Emphasis): Makes text italic. Semantically represents emphasized text. Screen readers will read emphasized text with more emphasis.
- <mark> (Marked): Highlights text, usually with a yellow background. Represents text that is relevant in some context. Good for search result highlights.
- <small> (Small): Makes text smaller. Represents side-comments and small print, like copyright notices.
- <del> (Deleted): Represents text that has been deleted from the document. Browsers typically render deleted text with a strikethrough.
- <ins> (Inserted): Represents text that has been inserted into the document. Browsers typically render inserted text with an underline.
- <sub> (Subscript): Renders text as subscript (small and below the baseline). Used for chemical formulas (e.g., H<sub>2</sub>O) or mathematical notations.
- <sup> (Superscript): Renders text as superscript (small and above the baseline). Used for exponents (e.g., x<sup>2</sup>) or footnotes.
Key Differences and Usage Considerations:
- <b> vs. <strong> and <i> vs. <em>: While <b> and <i> only provide visual styling, <strong> and <em> also convey semantic meaning. Use <strong> and <em> to indicate importance or emphasis, respectively. Use <b> and <i> only when you want bold or italic styling without implying importance or emphasis (e.g., for keywords in a product description, or for stylistic reasons). In modern web development, it’s often better to use CSS for styling and reserve semantic tags for meaning.
- <del> and <ins>: These are useful for showing edits in documents, such as in collaborative writing or version control systems.
Example:
2.2 Quotations and Citations: <q>, <blockquote>, <cite>, <address>
Explanation: These tags are used to represent quotations, citations, and contact information within an HTML document. They provide semantic meaning and help structure content logically.
- <q> (Quotation): Represents a short inline quotation. Browsers typically render <q> elements with quotation marks around the content.
- <blockquote> (Block Quotation): Represents a longer, block-level quotation. Browsers typically render <blockquote> elements with indentation. Often used for displaying quotes from external sources. The cite attribute can be used to specify the URL of the source of the quotation, although it’s not typically displayed visually.
- <cite> (Citation): Represents the title of a work (e.g., a book, article, song, movie). Often used within <blockquote or <p> elements to identify the source being quoted. Browsers typically render <cite> elements in italics.
- <address> (Address): Represents contact information for the author or owner of the document or article. May include physical address, email address, phone number, social media links, etc. Browsers typically render <address> elements in italics. Should not be used for arbitrary addresses (e.g., mailing address of a business, unless that’s also the contact information for the site owner).
Example:
2.3 Preformatted Text: <pre>
Explanation: The <pre> (preformatted text) element represents text that should be displayed exactly as it is written in the HTML source code, including spaces, tabs, and line breaks. Browsers typically render <pre> elements with a monospace font (like Courier New).
Use Cases:
- Displaying code snippets
- Displaying ASCII art
- Preserving the formatting of text documents
Example:
2.4 Comments in HTML: <! — … →
Explanation: Comments are used to add explanatory notes to your HTML code. They are ignored by the browser and are not displayed on the web page. Comments are essential for making your code more readable and maintainable.
Syntax: Comments start with <! — and end with →.
Example:
Best Practices:
- Use comments to explain complex or confusing code.
- Use comments to document the purpose of sections of code.
- Use comments to temporarily disable code during development.
- Don’t over-comment; only comment when necessary to improve clarity.
2.5 Character Entities: <, >, &,
Explanation: Character entities are used to display characters that are reserved in HTML or that are not easily typed on a keyboard.
Common Character Entities:
- < : Less than sign (<)
- > : Greater than sign (>)
- & : Ampersand (&)
- : Non-breaking space ( ) — Prevents the browser from collapsing multiple spaces into one.
- © : Copyright symbol (©)
- ® : Registered trademark symbol (®)
- ™ : Trademark symbol (™)
Why Use Them?
- Reserved Characters: < and > are used to define HTML tags. If you want to display these characters literally, you must use < and >. Similarly, & is used in character entity codes, so you must use & if you want to display an ampersand.
- Non-Breaking Space: Browsers typically collapse multiple spaces into a single space. If you need to display multiple consecutive spaces, use . This is useful for formatting text or creating visual separation.
- Special Characters: Some characters (like copyright symbols) may not be available on all keyboards or may not be properly encoded in the document. Character entities provide a reliable way to display these characters.
Example:
Chapter 3: Lists and Tables
3.1 Unordered Lists: <ul>, <li>
Explanation: An unordered list displays list items in no particular order, typically with bullet points.
Tags:
- <ul>: Defines the unordered list.
- <li>: Defines a list item within the unordered list.
Example:
Nesting: You can nest unordered lists within each other to create hierarchical lists.
3.2 Ordered Lists: <ol>, <li>, type attribute
Explanation: An ordered list displays list items in a specific order, typically with numbers or letters.
- Tags:
- <ol>: Defines the ordered list.
- <li>: Defines a list item within the ordered list.
type attribute: Specifies the type of marker to use for the list items. Possible values:
- 1: Numbers (default)
- a: Lowercase letters
- A: Uppercase letters
- i: Lowercase Roman numerals
- I: Uppercase Roman numerals
Example:
start Attribute: Specifies the starting value of the list.
Nesting: Ordered lists can also be nested, just like unordered lists.
3.3 Definition Lists: <dl>, <dt>, <dd>
Explanation: A definition list displays terms and their corresponding definitions. It’s often used for glossaries or describing terms.
Tags:
- <dl>: Defines the definition list.
- <dt>: Defines a term.
- <dd>: Defines the description of the term.
Example:
3.4 Basic Table Structure: <table>, <tr>, <th>, <td>
Explanation: Tables are used to display data in a structured format of rows and columns.
Tags:
- <table>: Defines the table.
- <tr>: Defines a table row.
- <th>: Defines a table header cell (usually bold and centered). Should be used for column headings.
- <td>: Defines a table data cell (normal data).
Example:
3.5 Table Headers, Rows, and Cells
Explanation: Reinforces the basic structure: A table consists of rows, and each row consists of cells. Table headers (<th>) are used to label the columns.
Best Practices:
- Always use <th> elements for column headings to improve accessibility and semantic meaning.
- Keep table structures simple and avoid deeply nested tables if possible. Complex layouts are better achieved with CSS.
3.6 Table Attributes: border, colspan, rowspan, width, height
Explanation: These attributes are used to customize the appearance and layout of tables.
border: Specifies the width of the table border. (Deprecated in HTML5; use CSS instead.)
colspan: Specifies the number of columns a cell should span.
<tr>
<th colspan="3">Personal Information</th>
</tr>
rowspan: Specifies the number of rows a cell should span.
<tr>
<th rowspan="2">Details</th>
<td>Name</td>
<td>John Doe</td>
</tr>
<tr>
<td>Age</td>
<td>30</td>
</tr>
width: Specifies the width of the table or a cell. (Deprecated in HTML5; use CSS instead.)
<table width="500"> ... </table> <!-- Avoid; use CSS instead -->
height: Specifies the height of the table or a cell. (Deprecated in HTML5; use CSS instead.)
<td height="50"> ... </td> <!-- Avoid; use CSS instead -->
Important: The border, width, and height attributes are deprecated. You should use CSS to style tables instead. This keeps your HTML structure separate from your presentation.
3.7 Table Captions: <caption>
Explanation: The <caption> element defines a caption for the table. It should be placed immediately after the <table> tag.
Example:
Accessibility: The <caption> provides context for the table, improving accessibility for users with screen readers.
3.8 Table Header, Body and Footer: <thead>, <tbody>, <tfoot>
Explanation: These elements provide semantic structure to tables, making them more accessible and easier to style.
- <thead>: Defines the table header section. Typically contains the <th> elements.
- <tbody>: Defines the main table body section. Contains the table data (<td> elements).
- <tfoot>: Defines the table footer section. Can be used for summaries, calculations, or other information that should appear at the bottom of the table.
Example:
Benefits:
- Semantic Meaning: Clearly defines the different parts of the table.
- Accessibility: Improves accessibility for users with screen readers.
- Styling: Allows you to apply specific styles to the header, body, and footer of the table using CSS.
- Printing: In long tables that span multiple pages when printed, the <thead> and <tfoot> can be configured to repeat on each page.
Chapter 4: Links and Images
4.1 Creating Hyperlinks: <a> tag, href attribute
Explanation: The <a> (anchor) tag is used to create hyperlinks, which allow users to navigate to other web pages, files, locations within the same page, or email addresses.
Tag and Attribute:
- <a>: Defines the hyperlink.
- href: Specifies the destination of the link.
- Example:
<a href="https://www.example.com">Visit Example Website</a>
target attribute: Specifies where to open the linked document. Common values:
- _self: Opens the linked document in the same window/tab (default).
- _blank: Opens the linked document in a new window/tab.
- _parent: Opens the linked document in the parent frame.
- _top: Opens the linked document in the full body of the window.
<a href="https://www.example.com" target="_blank">Visit Example Website in a New Tab</a>
Accessibility Consideration: Always provide descriptive link text that clearly indicates the destination of the link. Avoid generic phrases like “click here.”
4.2 Absolute vs. Relative URLs
Explanation: URLs (Uniform Resource Locators) specify the location of resources on the web. There are two main types of URLs: absolute and relative.
Absolute URL: Specifies the complete address of a resource, including the protocol (e.g., https://), the domain name (e.g., www.example.com), and the path to the resource (e.g., /images/logo.png). Use absolute URLs when linking to resources on other websites.
<a href="https://www.example.com/about">About Us</a> <img src="https://www.example.com/images/logo.png" alt="Example Logo"
Relative URL: Specifies the address of a resource relative to the current page. It only includes the path to the resource, not the protocol or domain name. Use relative URLs when linking to resources on the same website. This makes your site more portable (if you move it to a different domain, the links will still work) and easier to maintain.
<a href="about.html">About Us</a> <!-- Links to a file named "about.html" in the same directory. --> <img src="images/logo.png" alt="Example Logo"> <!-- Links to a file named "logo.png" inside an "images" folder in the same directory. -->
Relative URL Examples (assuming the current page is www.example.com/products/index.html):
- products.html: Links to www.example.com/products/products.html
- images/product.jpg: Links to www.example.com/products/images/product.jpg
- ../about.html: Links to www.example.com/about.html (moves one directory up)
- ../../contact.html: Links to www.example.com/contact.html (moves two directories up)
- /: Links to the root of the website: www.example.com/
4.3 Linking to Different Sections of the Same Page (Anchor Links)
Explanation: Anchor links allow you to link to specific sections of the same page. This is useful for long pages with multiple sections.
Steps:
- Assign an ID to the target element: Use the id attribute to give the element you want to link to a unique identifier.
<h2 id="section1">Section 1</h2> <p>Content of section 1...</p> <h2 id="section2">Section 2</h2> <p>Content of section 2...</p>
2. Create a link to the ID: Use the <a> tag with the href attribute set to # followed by the ID of the target element.
<a href="#section1">Go to Section 1</a> <a href="#section2">Go to Section 2</a>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Anchor Links Example</title>
</head>
<body>
<a href="#section1">Go to Section 1</a> | <a href="#section2">Go to Section 2</a>
<h2 id="section1">Section 1</h2>
<p>Content of section 1...</p>
<p>More content of section 1...</p>
<p>Even more content of section 1...</p>
<h2 id="section2">Section 2</h2>
<p>Content of section 2...</p>
<p>More content of section 2...</p>
</body>
</html>
4.4 Email Links: mailto:
Explanation: You can create links that automatically open the user’s email client and create a new email message.
Syntax: Use the mailto: scheme in the href attribute, followed by the email address.
<a href="me@example.com">Send me an email</a>
Adding Subject and Body: You can also pre-populate the subject and body of the email message using the subject and body parameters.
<a href="me@example.com?subject=Website Inquiry&body=Hello, I have a question about your website.">Send me an email with a subject and body</a>
Important Note: Be aware that mailto: links can be used by spammers to collect email addresses. Consider using a contact form instead for better security.
4.5 Inserting Images: <img> tag, src, alt, width, height attributes
Explanation: The <img> tag is used to embed images in your web pages.
Tag and Attributes:
- <img>: Defines the image. It’s a self-closing tag.
- src: Specifies the URL (path) of the image.
- alt: Specifies alternative text for the image. This text is displayed if the image cannot be loaded and is essential for accessibility (screen readers).
- width: Specifies the width of the image in pixels. (Deprecated; use CSS for styling.)
- height: Specifies the height of the image in pixels. (Deprecated; use CSS for styling.)
Example:
<img src="images/myimage.jpg" alt="A beautiful sunset" width="500" height="300">
Best Practices:
- Always include the alt attribute.
- Optimize images for the web to reduce file size and improve loading times.
- Use CSS to control the size and styling of images instead of the width and height attributes.
4.6 Image Formats: JPEG, PNG, GIF, WebP
Explanation: Different image formats are suitable for different types of images and use cases.
JPEG (or JPG): Best for photographs and images with complex colors. Uses lossy compression, which means some image data is discarded to reduce file size. Good for images where a little loss of quality is acceptable.
PNG: Best for images with sharp lines, text, logos, and images that require transparency. Uses lossless compression, which means no image data is lost. Good for images where quality is paramount.
GIF: Best for simple animations and images with limited colors. Uses lossless compression, but is limited to 256 colors. Mostly replaced by animated PNG or video formats.
WebP: A modern image format developed by Google that provides superior lossless and lossy compression for images on the web. Offers better quality and smaller file sizes compared to JPEG and PNG. Not supported by all older browsers, but support is growing rapidly.
Choosing the Right Format:
- Photographs: JPEG or WebP
- Logos, Graphics, Text: PNG or WebP
- Animations: GIF (but consider animated PNG or video formats)
4.7 Using Images as Links
Explanation: You can use an image as a hyperlink by placing the <img> tag inside the <a> tag.
Example:
<a href="https://www.example.com"> <img src="images/logo.png" alt="Example Logo"> </a>
Accessibility: When using an image as a link, make sure the alt attribute of the <img> tag accurately describes the destination of the link.
4.8 Figure and Figcaption: <figure>, <figcaption>
Explanation: The <figure> and <figcaption> elements are used to group an image (or other media) with a caption.
Tags:
- <figure>: Represents self-contained content, such as an image, illustration, diagram, code snippet, etc.
- <figcaption>: Defines a caption for the <figure> element. It can be placed either as the first or last child of the <figure> element.
Example:
<figure>
<img src="images/myimage.jpg" alt="A cat sleeping on a couch">
<figcaption>A cute cat sleeping peacefully on a couch.</figcaption>
</figure>
Benefits:
- Semantic Meaning: Clearly defines the image and its caption as a single unit of content.
- Accessibility: Improves accessibility for users with screen readers.
- Styling: Allows you to style the figure and caption as a single unit using CSS.
Chapter 5: Forms
5.1 The <form> Element and its Attributes: action, method (GET, POST)
Explanation: The <form> element is a container for input elements, such as text fields, checkboxes, radio buttons, and submit buttons. Forms are used to collect data from users.
Tag and Attributes:
- <form>: Defines the HTML form.
- action: Specifies the URL where the form data should be sent when the form is submitted. This is typically a server-side script (e.g., PHP, Python, Node.js) that will process the data.
- method: Specifies the HTTP method used to submit the form data. Common values:
- GET: Appends the form data to the URL (visible in the address bar). Should be used for non-sensitive data and when you don’t want to submit large amounts of data. GET requests can be bookmarked. Limited to a relatively short URL length (typically 2048 characters).
- POST: Sends the form data in the body of the HTTP request (not visible in the address bar). Should be used for sensitive data (e.g., passwords) and when submitting large amounts of data. POST requests cannot be bookmarked.
Example:
<form action="/submit-form.php" method="post"> <!-- Input elements will go here --> </form>
5.2 Input Fields: <input> tag, type attributes (text, password, email, number, date, checkbox, radio, submit, reset, file, hidden)
Explanation: The <input> element is the most versatile form element. The type attribute determines the type of input field to display.
Common type Attributes:
text: A single-line text input field.
<label for="name">Name:</label> <input type="text" id="name" name="name">
- password: A single-line text input field where the characters are masked (usually with asterisks).
<label for="password">Password:</label> <input type="password" id="password" name="password">
- email: A single-line text input field that validates whether the entered text is a valid email address (basic validation).
<label for="email">Email:</label> <input type="email" id="email" name="email">
- number: A single-line input field that allows only numbers to be entered. You can use the min, max, and step attributes to control the allowed range and increment.
<label for="age">Age:</label> <input type="number" id="age" name="age" min="0" max="120">
- date: A date picker input field.
<label for="birthday">Birthday:</label> <input type="date" id="birthday" name="birthday">
- checkbox: A checkbox that allows the user to select one or more options from a list.
<label for="option1"> <input type="checkbox" id="option1" name="options" value="option1"> Option 1 </label>
<label for="option2"> <input type="checkbox" id="option2" name="options" value="option2"> Option 2 </label>
- radio: A radio button that allows the user to select only one option from a list. Radio buttons with the same name attribute belong to the same group.
<label for="male"><input type="radio" id="male" name="gender" value="male"> Male </label>
<label for="female"><input type="radio" id="female" name="gender" value="female"> Female </label>
- submit: A button that submits the form data to the server.
<input type="submit" value="Submit">
- reset: A button that resets the form fields to their default values.
<input type="reset" value="Reset">
- file: An input field that allows the user to select a file from their computer.
<label for="file">Upload File:</label> <input type="file" id="file" name="file">
- hidden: A hidden input field that is not displayed on the page but can be used to store data that needs to be submitted with the form.
<input type="hidden" name="user_id" value="12345">
Key Attributes for <input>:
- id: A unique identifier for the input field. Used for linking with <label> elements and for styling/scripting.
- name: The name of the input field. This is the name that will be used to identify the data when the form is submitted to the server. Crucial.
- value: The initial value of the input field. For text, password, and email types, this is the text that will be displayed in the field. For checkbox and radio types, this is the value that will be submitted if the option is selected.
- placeholder: A hint that describes the expected value of the input field. The placeholder text disappears when the user starts typing.
- required: Specifies that the input field must be filled out before the form can be submitted.
- disabled: Disables the input field, making it unchangeable and un-submittable.
- readonly: Makes the input field read-only, but its value can still be submitted.
5.3 Text Areas: <textarea>
Explanation: The <textarea> element defines a multi-line text input field.
Tag and Attributes:
- <textarea>: Defines the text area.
- rows: Specifies the visible number of lines in the text area.
- cols: Specifies the visible width of the text area in characters.
- name: The name of the textarea element (required for form submission).
- id: A unique identifier for the textarea.
- placeholder: A hint that describes the expected input.
- required: Specifies that the textarea must be filled out.
- disabled: Disables the textarea.
- readonly: Makes the textarea read-only.
Example:
<label for="message">Message:</label><br> <textarea id="message" name="message" rows="4" cols="50"> </textarea>
5.4 Select Boxes: <select>, <option>, <optgroup>
Explanation: The <select> element defines a drop-down list (select box). The <option> elements define the options in the list. The <optgroup> element groups related options in a drop-down list.
Tags:
- <select>: Defines the select box.
- <option>: Defines an option in the select box.
- <optgroup>: Defines a group of related options.
- name: The name of the select element (required for form submission).
- id: A unique identifier for the select element.
- required: Specifies that an option must be selected.
- disabled: Disables the select box.
- multiple: Allows the user to select multiple options (using Ctrl/Cmd + Click).
Example:
<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br/>
<label for="country">Choose a country:</label>
<select id="country" name="country">
<optgroup label="Europe">
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="uk">United Kingdom</option>
</optgroup>
<optgroup label="Asia">
<option value="japan">Japan</option>
<option value="china">China</option>
</optgroup>
</select>
- selected Attribute: Specifies that an option should be pre-selected when the page loads.
<option value="volvo" selected>Volvo</option>
5.5 Buttons: <button>
Explanation: The <button> element defines a clickable button. It can be used to submit a form, reset a form, or perform other actions.
Tag and Attributes:
- <button>: Defines the button.
- type: Specifies the type of button. Possible values:
- submit: Submits the form. (Default if no type is specified)
- reset: Resets the form.
- button: A generic button that can be used to trigger JavaScript functions.
- name: The name of the button (if you want to submit a value with the button).
- value: The value that will be submitted with the button (if it has a name).
- disabled: Disables the button.
Example:
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<button type="button" onclick="alert('Hello!')">Click Me</button>
Advantages over <input type=”submit”>:
- You can include HTML content inside <button> elements (e.g., images, text formatting).
- The default type is submit, which is more intuitive.
5.6 Labels: <label>, for attribute
Explanation: The <label> element defines a label for an input element. It provides a user-friendly way to associate a text label with a form control.
Tag and Attributes:
- <label>: Defines the label.
- for: Specifies the id of the input element that the label is associated with.
Example:
<label for="username">Username:</label>
<input type="text" id="username" name="username">
Benefits:
- Accessibility: Improves accessibility for users with disabilities, especially those using screen readers. When a user focuses on a label, the associated input element also receives focus.
- Usability: Makes it easier for users to click or tap on form controls, especially on small screens. Clicking the label will focus the associated input.
- Implicit Labeling: You can also associate a label with an input element by placing the input element inside the <label> element. In this case, the for attribute is not required.
<label>Email: <input type="email" name="email"></label>
5.7 Fieldsets and Legends: <fieldset>, <legend>
Explanation: The <fieldset> element groups related form elements together. The <legend> element defines a caption for the <fieldset> element.
Tags:
- <fieldset>: Defines the fieldset.
- <legend>: Defines the legend (caption) for the fieldset.
Example:
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</fieldset>
Benefits:
- Organization: Visually groups related form elements, making the form easier to understand and navigate.
- Accessibility: Improves accessibility for users with screen readers. The <legend> provides a descriptive label for the entire group of form elements.
5.8 Form Attributes: required, readonly, disabled, placeholder
Explanation: These attributes enhance the functionality and usability of form elements.
required: Specifies that an input field must be filled out before the form can be submitted.
<input type="text" name="username" required>
- readonly: Makes an input field read-only, meaning the user cannot change its value. However, the value is still submitted with the form.
<input type="text" name="city" value="New York" readonly>
- disabled: Disables an input field, meaning the user cannot interact with it and its value is not submitted with the form.
<input type="text" name="country" value="USA" disabled>
- placeholder: Provides a hint inside the input field that describes the expected value. The placeholder text disappears when the user starts typing.
<input type="text" name="search" placeholder="Search...">
5.9 HTML5 Input Types: color, range, url, search, tel, datetime-local
Explanation: HTML5 introduced several new input types that provide specialized input fields with built-in validation and user interface elements.
color: A color picker input field.
<label for="favcolor">Favorite Color:</label>
<input type="color" id="favcolor" name="favcolor">
- range: A slider control that allows the user to select a value within a specified range. Use min, max, and step attributes to control the range and increment.
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100" step="1">
- url: A text input field that validates whether the entered text is a valid URL.
<label for="website">Website:</label>
<input type="url" id="website" name="website">
- search: A text input field optimized for search queries. May be styled differently by the browser.
<label for="search">Search:</label>
<input type="search" id="search" name="search">
- tel: A text input field optimized for telephone numbers. Does not enforce any specific format, but provides a more appropriate keyboard on mobile devices.
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone">
- datetime-local: Allows the user to select a date and time, without a timezone.
<label for="meeting-time">Choose a time for your meeting:</label>
<input type="datetime-local" id="meeting-time" name="meeting-time" value="2018-06-12T19:30" min="2018-06-07T00:00" max="2018-06-14T00:00">
5.10 Form Validation (basic)
Explanation: HTML5 provides built-in form validation features that allow you to validate user input on the client-side (before submitting the form to the server). This can improve the user experience by providing immediate feedback and reducing server load.
Built-in Validation Attributes:
- required: As mentioned before, makes an input field mandatory.
- type=”email”: Checks for a valid email address format.
- type=”number”: Checks for a valid number.
- min, max: Specifies the minimum and maximum values for number and range input types.
- minlength, maxlength: Specifies the minimum and maximum number of characters allowed in a text input field.
- pattern: Specifies a regular expression that the input value must match. This is the most powerful validation tool.
Example:
<form action="/submit-form.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required minlength="3" maxlength="20">
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="100">
<br><br>
<label for="postalcode">Postal Code:</label>
<input type="text" id="postalcode" name="postalcode" pattern="[0-9]{5}">
<br><br>
<input type="submit" value="Submit">
</form>
Important Considerations:
- Client-side validation is not a substitute for server-side validation. Always validate data on the server to prevent malicious attacks and ensure data integrity. Client-side validation is primarily for improving the user experience.
- Customize validation messages using JavaScript to provide more user-friendly feedback.
Chapter 7: HTML5 Multimedia
7.1 Embedding Audio: <audio>, src, controls, autoplay, loop, muted
Explanation: The <audio> element is used to embed audio content in your web pages.
Tag and Attributes:
- <audio>: Defines the audio content.
- src: Specifies the URL of the audio file. Alternatively, you can use multiple <source> tags inside the <audio> element (see section 7.5).
- controls: Displays audio controls (play, pause, volume, etc.). Highly recommended for usability.
- autoplay: Starts playing the audio automatically when the page loads. Use sparingly and with caution, as it can be annoying for users. Many browsers now block autoplay by default unless the user has interacted with the site.
- loop: Repeats the audio continuously.
- muted: Mutes the audio. Useful if you want to display a video with the sound off initially.
Example:
<audio src="https://www.w3schools.com/html/horse.ogg" controls autoplay loop muted</audio>
7.2 Embedding Video: <video>, src, controls, autoplay, loop, muted, width, height, poster
Explanation: The <video> element is used to embed video content in your web pages.
Tag and Attributes:
- <video>: Defines the video content.
- src: Specifies the URL of the video file. Alternatively, you can use multiple <source> tags inside the <video> element (see section 7.5).
- controls: Displays video controls (play, pause, volume, full-screen, etc.). Essential for usability.
- autoplay: Starts playing the video automatically when the page loads. Use sparingly.
- loop: Repeats the video continuously.
- muted: Mutes the video.
- width: Specifies the width of the video player in pixels. (Prefer using CSS.)
- height: Specifies the height of the video player in pixels. (Prefer using CSS.)
- poster: Specifies an image to be displayed while the video is downloading or until the user presses the play button.
- Example:
<video width="400" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
7.3 Supported Audio/Video Formats
Explanation: Not all browsers support the same audio and video formats. It’s important to use formats that are widely supported or provide multiple formats for different browsers.
Audio Formats:
- MP3: Widely supported, especially in modern browsers.
- WAV: Uncompressed audio format. Good quality but large file size.
- Ogg Vorbis: Open-source audio format. Supported by Firefox, Chrome, and Opera.
- AAC: Advanced Audio Coding. Generally offers better quality than MP3 at the same bitrate.
Video Formats:
- MP4: The most widely supported video format, especially when encoded with H.264 video codec and AAC audio codec.
- WebM: Open-source video format. Supported by Firefox, Chrome, and Opera.
- Ogg Theora: Open-source video format. Less common.
- MOV: Apple’s QuickTime video format.
- Best Practice: Provide multiple formats using the <source> element (see section 7.5) to ensure compatibility across different browsers.
7.4 Embedding YouTube Videos: <iframe>
Explanation: The <iframe> element is used to embed content from another website, such as a YouTube video.
Steps:
- Go to the YouTube video you want to embed.
- Click the “Share” button below the video.
- Click the “Embed” button.
- Copy the provided <iframe> code.
- Paste the <iframe> code into your HTML document.
Example:
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/qz0aGYrrlhU"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
- Replace VIDEO_ID with the actual ID of the YouTube video.
- The allowfullscreen attribute allows the user to view the video in full-screen mode.
- Security Note: Be cautious about embedding content from untrusted sources, as it could pose a security risk.
7.5 The <source> Element for Multiple Media Sources
Explanation: The <source> element allows you to specify multiple media files for the <audio> or <video> element. The browser will choose the first source that it supports. This is essential for ensuring compatibility across different browsers.
Tag and Attributes:
- <source>: Specifies a media resource for <audio>, <video>, or <picture>.
- src: Specifies the URL of the media file.
- type: Specifies the MIME type of the media file (e.g., audio/mp3, video/mp4).
Example:
<video controls width="640" height="360" poster="thumbnail.jpg">
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<p>Your browser does not support HTML5 video.</p>
</video>
<audio controls>
<source src="audio.mp3" type="audio/mp3">
<source src="audio.ogg" type="audio/ogg"> Your browser does not support the audio element.
</audio>
Important: The order of the <source> elements matters. The browser will try the first source, then the second, and so on, until it finds a format it supports.
7.6 The <track> element for captions.
Explanation: The <track> element is used to add captions, subtitles, descriptions, or other metadata to <video> elements. This is essential for accessibility, allowing users who are deaf or hard of hearing to understand the video content.
Tag and Attributes:
- <track>: Specifies a text track for <video> elements.
- src: Specifies the URL of the text track file (usually a .vtt file).
- kind: Specifies the kind of text track. Common values:
- subtitles: Subtitles for viewers who don’t understand the language.
- captions: Captions for viewers who are deaf or hard of hearing (includes sound cues and descriptions).
- descriptions: Textual descriptions of the video content (for users who are blind or have low vision).
- metadata: Metadata for use by JavaScript.
- srclang: Specifies the language of the text track (e.g., “en” for English, “es” for Spanish).
- label: Specifies a user-readable title for the text track.
- default: Specifies that the text track should be enabled by default.
- VTT (WebVTT) File Format: VTT is a plain text file format for text tracks. It contains timing cues and the corresponding text.
- Example:
<video controls width="640" height="360" poster="thumbnail.jpg">
<source src="video.mp4" type="video/mp4">
<track src="captions_en.vtt" kind="captions" srclang="en" label="English" default>
<track src="subtitles_es.vtt" kind="subtitles" srclang="es" label="Spanish">
Your browser does not support HTML5 video.
</video>
- Example VTT File (captions_en.vtt):
WEBVTT 00:00:00.000 --> 00:00:05.000 Hello, everyone! Welcome to my video. 00:00:05.000 --> 00:00:10.000 Today, we're going to be talking about HTML5 multimedia.
This post is based on interaction with https://aistudio.corp.google.com.
Happy learning :-)