Attributes
Adding extra information and behavior to elements with name-value pairs
Overview
Attributes provide additional information about an element, written as name-value pairs inside the opening tag. They control things like where a link points, what an image shows if it fails to load, and unique identifiers for styling and scripting. Nearly every element accepts attributes, so they are essential to writing useful HTML.
Syntax / Usage
Attributes go inside the opening tag, after the tag name. The value is wrapped in quotes.
<!-- name="value" pairs inside the opening tag -->
<a href="https://example.com" target="_blank">Visit</a>
<!-- Multiple attributes are separated by spaces -->
<img src="cat.jpg" alt="A sleeping cat" width="300" />
<!-- Global attributes work on almost any element -->
<p id="intro" class="lead" title="Introduction">Hello</p>
<!-- Boolean attributes need no value -->
<input type="checkbox" checked />
Examples
Using id and class for hooks that CSS and JavaScript can target:
<button id="save-btn" class="btn btn-primary">Save</button>
A custom data-* attribute storing extra information:
<li data-product-id="42" data-price="9.99">Notebook</li>
Common Mistakes
- Omitting quotes around values, which fails when values contain spaces
- Reusing the same
idon multiple elements;idmust be unique per page - Forgetting the
altattribute on images, hurting accessibility - Confusing
class(reusable) withid(unique) - Adding a value to boolean attributes like
checkedordisabledunnecessarily
See Also
html-elements-and-tags html-links-and-images html-forms