Skip to content

CSS Tutorial CSS Selectors

CSS ID Selector

Lesson 9 of 182 2 min read By Deepak Paswan Updated Oct 4, 2026

An ID is a name for one single element on a page. You set it with the id attribute and select it in CSS with a hash #.

index.html
HTML
<style>
  #main-title {
    color: #d94a00;
    letter-spacing: 1px;
  }
</style>
<h1 id="main-title">Welcome to Juniper Books</h1>
<h1>This heading has no ID</h1>

Rules for IDs

  • An ID must be unique. Two elements with id="main-title" on the same page is an error in HTML.
  • IDs are case sensitive and cannot contain spaces.
  • An element can have an ID and classes at the same time.

ID or class?

ClassID
Selector.name#name
Use on many elementsYesNo, one only
Strength in CSSNormalMuch stronger

IDs are very strong in the cascade, which is exactly why many developers avoid them for styling. A rule like #sidebar a is hard to override later without writing an even stronger rule. Classes are easier to reuse and easier to change.

IDs are still useful, just not mostly for CSS. They are the target of in-page links (<a href="#contact"> jumps to id="contact"), form labels and JavaScript.

info
Use IDs for linking, classes for styling
A good default: if you only need to make something look different, use a class.
warning
Reusing an ID
When two elements share an ID, CSS usually styles both, so you may not notice. But links, labels and scripts will only find the first one, and validators will report an error.