๐ŸŽ“ A1Learner
๐Ÿ”
0 of 50 lessons completed

HTML Classes and IDs

A class attribute is a shared name that can mark many elements. An id attribute is a unique name that marks only one element.

One class on two paragraphs

Both paragraphs carry the same class name. The class name here is note.

<p class="note">First note for readers.</p>
<p class="note">Second note for readers.</p>

Two different classes

Different class names mark different kinds of element. Styles can treat each kind in its own way.

<p class="note">A small note.</p>
<p class="warning">A strong warning.</p>

An id on one heading

The id top marks this heading only. No other element on the page may use that id.

<h2 id="top">Top Stories</h2>
<p>Read the biggest story first.</p>

Class and id together

One element can carry both a class and an id. The class groups it, and the id singles it out.

<p id="main-note" class="note">The most important note.</p>
<p class="note">A regular note.</p>

Example

<!DOCTYPE html>
<html>
<head>
<title>Classes and IDs</title>
</head>
<body>
<h1 id="page-title">Book Club</h1>
<p class="intro">We meet every Friday evening.</p>
<p class="note">Bring the book you are reading.</p>
<p class="note">New members are welcome.</p>
</body>
</html>

Key points

  • Class: a shared name that many elements can carry
  • Id: a unique name that only one element can carry
  • Many elements can share one class, but one id belongs to a single element.
  • Use class to group elements that should look or act the same
  • Use id to single out one element on the page
  • CSS: a styling language that can target a class or an id

In this example, the heading carries the id page-title. That id marks the heading alone. The first paragraph carries the class intro. The last two paragraphs share the class note. CSS or JavaScript can now find the heading by its id. They can also find both notes by their shared class.

Note

A class or id name cannot start with a number.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which statement about the id attribute is true?