HTML Attributes
What are HTML Attributes?
HTML attributes provide additional information about HTML elements. They are always specified in the opening tag and usually come in name/value pairs like: name="value".
Common Attributes
The id Attribute
The id attribute specifies a unique identifier for an element. It must be unique within the HTML document:
<h1 id="main-heading">Welcome</h1>
<p id="intro-paragraph">This is an introduction.</p>
The class Attribute
The class attribute is used to specify one or more class names for an element. Multiple elements can share the same class:
<p class="intro">First paragraph</p>
<p class="intro">Second paragraph</p>
<div class="container main">Content</div>
The style Attribute
The style attribute is used to add inline CSS styles to an element:
<p style="color: blue; font-size: 20px;">Styled paragraph</p>
<h1 style="background-color: yellow;">Colored heading</h1>
The title Attribute
The title attribute provides additional information about an element. It appears as a tooltip when you hover over the element:
<p title="This is a tooltip">Hover over this text</p>
<abbr title="HyperText Markup Language">HTML</abbr>
The lang Attribute
The lang attribute declares the language of the web page or element:
<html lang="en">
<p lang="fr">Bonjour le monde</p>
<p lang="es">Hola mundo</p>
Element-Specific Attributes
Anchor Tag Attributes
The <a> tag uses the href attribute to specify the link destination:
<a href="https://www.example.com">Visit Example</a>
<a href="page.html" target="_blank">Open in new tab</a>
Image Tag Attributes
The <img> tag uses src for the image source and alt for alternative text:
<img src="photo.jpg" alt="A beautiful landscape">
<img src="logo.png" alt="Company logo" width="200" height="100">
Input Tag Attributes
The <input> tag uses various attributes depending on the input type:
<input type="text" name="username" placeholder="Enter username">
<input type="email" name="email" required>
<input type="password" name="password" minlength="8">
Boolean Attributes
Some attributes don't require a value. These are called boolean attributes:
<input type="checkbox" checked>
<button disabled>Disabled Button</button>
<video autoplay muted></video>
Best Practices
- Always use lowercase for attribute names
- Always quote attribute values
- Use semantic attributes when possible
- Provide alt text for images
- Use meaningful id and class names