What are HTML Attributes and How Do They Work?
Answer
HTML attributes provide additional information about elements. They are placed inside the opening tag and usually come in name-value pairs.
Syntax
<element attribute="value">Content</element>
Attribute Structure
Common Global Attributes
These work on any HTML element:
| Attribute | Purpose | Example |
|---|---|---|
id | Unique identifier | <div id="header"> |
class | CSS class(es) | <p class="intro bold"> |
style | Inline CSS | <span style="color: red;"> |
title | Tooltip text | <abbr title="HyperText">HT</abbr> |
data-* | Custom data | <div data-user-id="42"> |
hidden | Hide element | <p hidden>Secret</p> |
Element-Specific Attributes
<!-- Image attributes -->
<img src="photo.jpg" alt="Description" width="300" height="200" />
<!-- Link attributes -->
<a href="https://example.com" target="_blank" rel="noopener">Visit</a>
<!-- Input attributes -->
<input type="email" name="email" placeholder="Enter email" required />
<!-- Form attributes -->
<form action="/submit" method="POST" enctype="multipart/form-data"></form>
Boolean Attributes
Some attributes don't need values - their presence is enough:
<!-- These are equivalent -->
<input disabled />
<input disabled="disabled" />
<input disabled="" />
<!-- Common boolean attributes -->
<input type="checkbox" checked />
<button disabled>Can't Click</button>
<video autoplay muted loop>
<script defer src="app.js"></script>
</video>
Attribute Best Practices
<!-- ✅ Good: Use double quotes -->
<div class="container">
<!-- ✅ Good: Lowercase attribute names -->
<img src="image.jpg" alt="Photo" />
<!-- ❌ Avoid: Unquoted values (works but risky) -->
<div class="container">
<!-- ❌ Avoid: Missing alt for images -->
<img src="image.jpg" />
</div>
</div>
Key Points
- Attributes modify element behavior or appearance
- Always use quotes around attribute values
- Keep attribute names lowercase (HTML5 standard)
- Some attributes are required (like
altfor<img>) - Boolean attributes don't need values