Skip to content

HTML Tutorial Elements and Attributes

HTML id and class Attributes: Naming Elements for CSS and JavaScript

Lesson 10 of 81 2 min read By Deepak Paswan Updated Oct 4, 2026

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.

index.html
HTML
<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.

index.html
HTML
<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

Featureidclass
How many elementsOneMany
Per elementOne idSeveral classes
CSS selector#name.name
Use forUnique things, link targetsShared styling

Choosing names

  • Use lowercase letters, numbers and hyphens: main-menu, price-table.
  • Name by purpose, not appearance. warning is better than red-box, because the colour may change later.
  • Do not start an id with a number, and avoid spaces.
warning
Repeating an id
If two elements share an id, JavaScript and links only find the first one, and validators report an error. Use a class when you need the same name more than once.

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
index.html
HTML
<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>