What Are Attributes?
Attributes provide extra information about an element. They go inside the opening tag as name="value" pairs:
<a href="https://google.com" target="_blank" class="btn">Visit Google</a>
^ ^ ^
attribute attribute attribute
class — For Styling
The class attribute lets you apply CSS to multiple elements. Many elements can share the same class:
<p class="highlight">This will be styled.</p>
<p class="highlight">This too.</p>
<p>This will NOT be styled.</p>
An element can have multiple classes (space-separated):
<button class="btn btn-primary large">Sign Up</button>
id — Unique Identifier
The id marks a unique element. No two elements should share the same id:
<header id="top">...</header>
<section id="features">...</section>
<footer id="contact">...</footer>
Common uses:
- Jump links:
<a href="#features">See Features</a> - JavaScript:
document.getElementById("contact")
Useclassfor styling (applies to many). Useidfor unique elements you target with links or JavaScript.
style — Inline CSS
The style attribute applies CSS directly to one element. Use sparingly:
<p style="color: red; font-size: 18px;">This text is red.</p>
<div style="background: #f5f5f5; padding: 20px; border-radius: 8px;">A card.</div>
Common Attributes Quick Reference
| Attribute | Used on | Purpose |
|---|---|---|
href | <a> | Link destination |
src | <img>, <script> | File source path |
alt | <img> | Alternative text |
placeholder | <input> | Hint text in empty field |
required | inputs | Makes field mandatory |
disabled | inputs, buttons | Disables the element |
target="_blank" | <a> | Opens link in new tab |
lang | <html> | Declares page language |
data-* Attributes — Custom Data
Store custom data on any element. JavaScript can read it later:
<button class="add-to-cart" data-product-id="42" data-price="299">Add to Cart</button>
// Reading data attributes in JavaScript
const btn = document.querySelector(".add-to-cart");
console.log(btn.dataset.productId); // "42"
console.log(btn.dataset.price); // "299"
Boolean Attributes
Some attributes are boolean — their presence means true:
<input type="text" required>
<input type="checkbox" checked>
<input type="text" disabled>
<video src="intro.mp4" autoplay muted loop></video>
Try It Yourself
- Give each section of your page a unique
id - Add jump links in your nav pointing to those ids
- Add
class="card"to 3 article divs - Store a
data-categoryattribute on each tutorial link