id and class are the two attributes that let you point at elements from CSS and JavaScript. They look similar but behave differently.
id: one unique name
An id identifies one element. Each id can be used only once on a page.
<h2 id="opening-hours">Opening hours</h2>
<style>
#opening-hours { color: #b84624; }
</style>
In CSS you select an id with #. You can also link straight to it with #opening-hours in a URL, which you will use in Bookmarks and Fragment Links.
class: a reusable name
A class can be used on as many elements as you like, and one element can have several classes separated by spaces.
<p class="note">Used books are half price on Sundays.</p>
<p class="note highlight">New arrivals this week.</p>
<style>
.note { border-left: 4px solid #ca4b00; padding-left: 8px; }
.highlight { background: #fff3ec; }
</style>
In CSS you select a class with a dot: .note.
Quick comparison
| Feature | id | class |
|---|---|---|
| How many elements | One | Many |
| Per element | One id | Several classes |
| CSS selector | #name | .name |
| Use for | Unique things, link targets | Shared styling |
Choosing names
- Use lowercase letters, numbers and hyphens:
main-menu,price-table. - Name by purpose, not appearance.
warningis better thanred-box, because the colour may change later. - Do not start an id with a number, and avoid spaces.
Repeating an id
Exercise: id and class together
Create two paragraphs with the class tip and one heading with the id tips-title. Add CSS that makes all tip paragraphs italic.
Show a possible solution
<h2 id="tips-title">Reading tips</h2>
<p class="tip">Read a few pages before you decide.</p>
<p class="tip">Keep a notebook nearby.</p>
<style>
.tip { font-style: italic; }
</style>