The content of an HTML document is structured using elements. An element is the complete component, consisting of a starting tag, its attributes, the content, and an ending tag.
1. Elements vs. Tags
While often used interchangeably, tags are only the markers used to create an element.
- Tags: The explicit markers surrounded by angle brackets (
<tag>). There are opening tags (e.g.,<h1>) and closing tags (e.g.,</h1>). - Element: Everything from the opening tag to the closing tag, including all the content.
Example
<p>This is the content of the paragraph element.</p>
2. Nesting Elements
Elements are structured in a parent-child hierarchy, meaning they are nested inside one another.
- The
<html>element is the root and the ultimate parent. - The
<head>and<body>are children of<html>. - A
<body>element might contain a paragraph<p>, making<p>the child and<body>the parent.
Crucial Rule: Elements must be properly nested (i.e., the last tag opened must be the first tag closed).
<div><p>Hello.</p></div>
<div><p>Hello.</div></p>
3. Void (Self-Closing) Elements
Most elements require content and therefore need both opening and closing tags. However, some elements are used simply to insert something into the page (e.g., an image or a line break) and cannot contain content. These are called void elements or self-closing tags.
| Tag | Purpose | Example |
<br> | Line break (moves text to the next line). | Line 1<br>Line 2 |
<img> | Embeds an image. | <img src="pic.jpg"> |
<hr> | Thematic break (draws a horizontal line). | <hr> |
<input> | Creates an input field in a form. | <input type="text"> |
In HTML5, the trailing slash (e.g.,
<br />) is optional and is usually omitted for simplicity.
4. Attributes
Attributes are used inside the opening tag of an element to provide additional information or modify the element’s behavior.
- Syntax:
name="value" - Rule: Attributes are always placed in the opening tag and are typically written in lowercase. The value should always be enclosed in double quotes (
").
A. Common Global Attributes
These attributes can be used on almost every HTML element:
class: Used to assign a style name for CSS (e.g.,class="highlighted").id: Used to assign a unique identifier to an element (e.g.,id="main-nav").style: Used to apply inline CSS styles (avoid for complex styling).title: Provides extra information, often displayed as a tooltip on hover.
B. Element-Specific Attributes
These attributes are mandatory or specific to certain tags:
href: Used with the<a>(link) tag to specify the destination URL.src: Used with the<img>or<script>tags to specify the source (path) of a file.alt: Used with the<img>tag to provide alternative text for screen readers or when the image fails to load.
Example: Element with Attributes
<img src="logo.png" alt="Company Logo" width="100">
