EthicsComputerCourses
Join training +91 90532 10052

ID Selectors

CSS · Lesson 13 of 240 Beginner 10 min read Updated

By the end of this lesson you will be able to write an ID selector, explain what the browser does when an ID is not unique, show why professional teams rarely style with IDs, and use IDs for the jobs they are good at: jump links and the :target highlight.

You met ID selectors briefly in CSS Selectors Fundamentals, and Classes & IDs covered the HTML side: naming rules and every attribute that points at an id. This lesson stays on the CSS side and keeps using the Tarang 2026 fest page from Class Selectors.

What an ID selector is

An ID selector is a hash sign followed by an id, such as #register. It matches the element whose id attribute is exactly that value.

CSS
#register {
  background: #fce4ec;
  padding: 1.5rem;
}
HTML
<section id="register">
  <h2>Register for events</h2>
</section>

An id is meant to be unique on the page. Think of the roll number on Meera's college ID card. Many students share the class "final year", but only Meera has roll number 21CS047. A class says "one of a group"; an id says "this exact one".

Like class names, ids are case-sensitive: #Register does not match id="register". And like classes, an id that starts with a digit cannot be written directly as a CSS selector, so start every id with a letter.

Step 1: give one section its own look

The Tarang page has a navigation menu that jumps to three sections. Each section has an id, and the registration section gets a special background through an ID selector.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ID selector</title>
  <style>
    body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.6; }
    nav { padding: 0.8rem 1rem; background: #4a148c; }
    nav a { color: white; margin-right: 1rem; }
    section { padding: 1rem 1rem 6rem; }
    #register {
      background: #fce4ec;
      border-top: 4px solid #c2185b;
    }
  </style>
</head>
<body>
  <nav>
    <a href="#events">Events</a>
    <a href="#register">Register</a>
    <a href="#venue">Venue</a>
  </nav>
  <section id="events">
    <h2>Events</h2>
    <p>Battle of the Bands, hackathon, street play, robo race and more.</p>
  </section>
  <section id="register">
    <h2>Register</h2>
    <p>Registration closes on 5 December at 6 pm. Bring your college ID to the help desk.</p>
  </section>
  <section id="venue">
    <h2>Venue</h2>
    <p>Main campus, near the old hostel gate. Nearest bus stop: Shivajinagar.</p>
  </section>
</body>
</html>

What you should see: a purple menu bar and three sections, with only "Register" in pink. Click a menu link and the page jumps to that section. The href="#register" link and the #register selector both use the same id, which is the main reason ids exist: to name one exact spot on the page.

Uniqueness: what really happens with a duplicate id

The HTML standard says an id must be unique. But what if a page breaks that rule? The answer surprises many developers: CSS does not check. An ID selector styles every element that has that id. Everything else, though, only finds the first one.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Duplicate id</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; }
    .day { padding: 0.8rem; margin-bottom: 8rem; border: 2px solid #ddd; }
    #prize { color: #2e7d32; font-weight: bold; }
    :target { outline: 4px solid #ffb300; }
  </style>
</head>
<body>
  <p><a href="#prize">Jump to the prize list</a></p>
  <div class="day">
    <h2>Day 1</h2>
    <p id="prize">Prizes: ₹10,000 for the best band</p>
  </div>
  <div class="day">
    <h2>Day 2</h2>
    <p id="prize">Prizes: ₹25,000 for the hackathon winners</p>
  </div>
  <p id="info"></p>
  <script>
    document.getElementById("info").textContent =
      "getElementById found: " + document.getElementById("prize").textContent;
  </script>
</body>
</html>

What you should see: both prize lines are green and bold, because the #prize rule matched both. Now click the link. The page jumps to the Day 1 prize only, and only that one gets the gold :target outline. The line at the bottom shows that JavaScript's getElementById() also returned the Day 1 element.

So a duplicate id "works" for styling and quietly breaks links, labels, :target, accessibility attributes and scripts. Browsers show no error. This is why you should never copy an element that has an id without renaming it. An HTML validator catches duplicates for you.

Why teams avoid styling with IDs

IDs are excellent for pointing at things. For styling, most teams avoid them. There are three reasons.

Reason 1: an ID selector is very strong

Specificity is the score the browser uses when two rules disagree. An ID selector scores (1, 0, 0). A class scores (0, 1, 0). The first column is compared first, so one ID beats any number of classes. You will learn the full scoring in CSS Specificity; for now, see what it means in practice.

Step 2: the button that will not turn grey

Kabir styles the registration button with an ID. On 5 December registration closes, so Farhan adds a closed class to make the button grey. Run it.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ID specificity</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; }
    #register-btn {
      padding: 0.6rem 1.2rem;
      border: 0;
      border-radius: 8px;
      background: #c2185b;
      color: white;
      font: inherit;
    }
    /* Added later, but it loses */
    .closed {
      background: #9e9e9e;
    }

    /* The class-based version */
    .btn {
      padding: 0.6rem 1.2rem;
      border: 0;
      border-radius: 8px;
      background: #c2185b;
      color: white;
      font: inherit;
    }
    .btn.is-closed {
      background: #9e9e9e;
    }
  </style>
</head>
<body>
  <p>Styled with an ID:</p>
  <button type="button" id="register-btn" class="closed">Register now</button>
  <p>Styled with classes:</p>
  <button type="button" class="btn is-closed">Register now</button>
</body>
</html>

What you should see: the first button is still pink. The .closed rule comes later in the file, but order only matters when specificity is equal, and the ID wins first. To fix it, Farhan would need an even stronger selector such as #register-btn.closed, or !important, and the next person would have to go stronger still. The second button uses classes only, so a chained class beats the base class and turns it grey, with no fight.

Reason 2: an ID cannot be reused

The fest page later needs a second "Register now" button at the bottom. With #register-btn, Kabir must copy the whole rule under a new id. With .btn, he simply adds the class again.

Reason 3: ids already have other jobs

The same id is often used by a jump link, a <label for>, an ARIA attribute and a script. If a developer renames it for one of those jobs, the styles silently break too. Keeping styles on classes means each part of the code can change without hurting the others.

Where IDs are the right tool

Use ids freely for the things only an id can do:

  • Fragment links. The part of a URL after # is called the fragment. A link to #venue scrolls to the element with id="venue", and a link to tarang.example/#venue opens the page at that spot.
  • Form labels. <label for="email"> connects to <input id="email">.
  • Accessibility references, such as aria-describedby.
  • JavaScript hooks, through getElementById().

Fragments and :target

When a fragment points at an element, CSS lets you style that element with the :target pseudo-class. A pseudo-class selects an element by its state rather than its name. Here the state is "I am the element named in the URL", which is how the Day 1 prize got its gold outline above.

A common use is highlighting the section a visitor just jumped to, so they do not lose their place in a long page. Notice that :target styles the element through its state, so you get the highlight without writing a single ID selector. You will meet more pseudo-classes in Pseudo-Class Selectors.

Common mistakes

  • Writing the same id twice. CSS styles both, but links, labels and scripts only find the first.
  • Using # in the HTML. id="#register" creates an id that literally starts with a hash. Write id="register".
  • Fighting an ID with !important. Change the ID selector to a class instead.
  • Mixing up case. #Venue does not match id="venue".
  • Styling with the same id a script depends on. Renaming it for one job breaks the other.

Interview questions

1. What happens if two elements share the same id?

The page is invalid HTML, but the browser does not report an error. An ID selector in CSS styles both elements. However, getElementById(), fragment links, :target and <label for> all use only the first element in the document, so behaviour quietly breaks.

2. Why do style guides discourage ID selectors?

An ID selector has specificity (1, 0, 0), so it beats any number of classes and is hard to override without longer selectors or !important. It also cannot be reused on a second element. Classes keep specificity low and flat, which makes stylesheets easier to maintain.

3. How can you target an element by its id without the high specificity?

Use the attribute selector [id="name"]. It matches the same element but has the specificity of a class, (0, 1, 0). This is useful when you cannot change third-party HTML.

4. What is the :target pseudo-class?

It matches the element whose id equals the URL's fragment, the part after #. When a user follows a link to #venue, the element with id="venue" matches :target. It is often used to highlight the section someone jumped to.

5. What are ids actually good for in front-end code?

Fragment links, connecting labels to form controls, ARIA references such as aria-describedby, and finding one element in JavaScript. These all need one unique target, which is exactly what an id provides.

Key points

  • An ID selector is # plus an id, like #register, and targets the element with that id.
  • Ids must be unique; CSS still styles duplicates, but links, labels, :target and scripts use only the first.
  • An ID selector scores (1, 0, 0), so it beats any number of classes and is hard to override.
  • Prefer classes for styling; keep ids for fragment links, labels, ARIA and JavaScript.
  • [id="name"] matches by id with class-level specificity.
  • :target styles the element named in the URL's fragment.

Exercise

Build a one-page "Tarang 2026 workshops" list with three links at the top (Photography, Robotics, Folk dance) and three matching sections further down, each with an id and a short answer. Style the sections with a class, not with ids. Use :target to give the section the visitor jumped to a coloured left border and a light background. Then add one <button> with both an id (for a future script) and a class, and style it only through the class.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Tarang 2026 workshops</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; }
    .workshop { padding: 0.8rem 1rem; margin-bottom: 10rem; border-left: 5px solid #ddd; }
    :target { border-left-color: #c2185b; background: #fce4ec; }
    .help-btn { padding: 0.5rem 1rem; border: 0; border-radius: 6px; background: #4a148c; color: white; }
  </style>
</head>
<body>
  <ul>
    <li><a href="#photography">Photography</a></li>
    <li><a href="#robotics">Robotics</a></li>
    <li><a href="#folk-dance">Folk dance</a></li>
  </ul>
  <section class="workshop" id="photography"><h2>Photography</h2><p>Bring a phone or camera. Room 204, 10 am.</p></section>
  <section class="workshop" id="robotics"><h2>Robotics</h2><p>Kits provided, ₹200 per team. Lab 3, 2 pm.</p></section>
  <section class="workshop" id="folk-dance"><h2>Folk dance</h2><p>Lavani basics with Isha. Open-air stage, 5 pm.</p></section>
  <button type="button" id="call-help" class="help-btn">Call a volunteer</button>
</body>
</html>

The sections share the workshop class for their look, and the ids exist only for the links and :target. The button's id is free for a script, while its look stays on .help-btn, which any other button can reuse.

Quick Quiz

1. Two paragraphs both have id="note". What does #note { color: red; } do?

2. A button has id="buy" and class="disabled". #buy sets a blue background and a later .disabled rule sets grey. What colour is the button?

3. Which selector matches id="banner" but with the specificity of a class?

4. A visitor opens fest.example/#venue. Which element matches :target?

Learn CSS with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call