4. HTML Attributes
HTML attributes provide additional information about an element. Attributes are written in the opening tag of an element and are always specified as name-value pairs.
Syntax of HTML Attributes
The general syntax of an attribute is as follows:
<element attribute="value">Content</element>
For example, the <img>
element uses the src
and alt
attributes:
<img src="image.jpg" alt="Description of image">
Common HTML Attributes
- id: Specifies a unique identifier for an element.
- class: Specifies one or more class names for an element, used for styling with CSS.
- src: Specifies the source of an image (used in
<img>
). - href: Specifies the destination of a link (used in
<a>
). - alt: Provides an alternate text description for an image (used in
<img>
). - title: Specifies additional information about an element (appears as a tooltip when the mouse hovers over the element).
Example: Using HTML Attributes
Below is an example showing how multiple attributes can be used in an element:
<a href="https://www.example.com" target="_blank" title="Visit Example">Click Here</a>
This example creates a link that opens in a new tab and shows a tooltip when hovered.
Global Attributes
There are several attributes that can be used with any HTML element, called global attributes. Some common global attributes include:
- id: A unique identifier for the element.
- class: Defines one or more class names.
- style: Defines inline CSS styles for the element.
- title: Provides additional information, typically shown as a tooltip.
Example: Global Attributes
<div id="container" class="content-box" style="background-color: lightblue;" title="Content Box">
<p>This is a paragraph inside a div with global attributes.</p>
</div>
In this example, the <div>
element has the id
, class
, style
, and title
attributes applied.
Conclusion
HTML attributes are a vital part of building web pages. They provide additional functionality and enhance the accessibility, presentation, and interactivity of HTML elements. In the next lesson, we will learn about HTML Forms and their attributes.