agyanadda@gmail.com

HTML Classes and IDs

HTML Layout & Structure 1 min read Updated Nov 30, 2026 Topic 17 of 33

class and id give names to elements so CSS and JavaScript can find them.

class

  • Can be used on many elements.
  • One element can have several classes: class="card featured".
  • In CSS, select it with a dot: .card { }.

id

  • Must be unique — only one element per page.
  • In CSS, select it with a hash: #header { }.
  • Also used for page links: <a href="#contact"> jumps to the element with id="contact".

Rule of thumb: use class for styling, id for one unique element or page jumps.

Example

Example — Classes and IDs with CSS HTML
<style>
  .note { background: #fff8e1; padding: 10px; border-left: 4px solid orange; }
  .important { font-weight: bold; }
  #title { color: #1e3a8a; }
</style>

<h1 id="title">Classes and IDs</h1>
<p class="note">This is a note.</p>
<p class="note important">This note is also important.</p>

Test Yourself With Exercises

Exercise 1 Multiple Choice

How do you select class="card" in CSS?

Exercise 2 True / False

Two elements on the same page should share one id.

Exercise 3 Fill in the Blank

In CSS, an id is selected with the ___ symbol.

Frequently Asked Questions

Yes, for example <section id="contact" class="box">.