What is the difference between id and class selectors?

LowEasyCss
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

An id is unique on a page and selected with #id; a class can be reused and selected with .class. IDs have higher specificity and are often used for anchors or JS hooks, while classes are for styling groups.

Answer

Overview

In CSS, id and class selectors target elements for styling or scripting, but they serve different purposes. IDs are unique identifiers for single elements, while classes group multiple elements under a shared style.

Aspect

id Selector

class Selector

Syntax

elementID

.elementClass

Uniqueness

Must be unique per page

Can be used on multiple elements

Specificity

Higher (overrides class styles)

Lower (can be overridden by id)

Use Case

For specific, unique components

For reusable, shared styles

Example HTML

<div id='header'></div>

<div class='card'></div>

Differences between id and class selectors

Example: Styling with id and class

CSS
#header {
  background: #0ea5e9;
  color: white;
}

.card {
  border: 1px solid #cbd5e1;
  padding: 12px;
  border-radius: 6px;
}
                  

Here, #header targets a unique section, while .card can style multiple elements throughout the page.

Best Practices

      • Use id for elements that occur only once (like navigation bars or main headers).
      • Use class for groups of similar elements that share styling.
      • Avoid overusing IDs in CSS — they increase specificity and reduce maintainability.
      • Use class selectors in component-based systems like React or Angular for modularity.

Specificity Hierarchy
CSS calculates priority using a scoring system. IDs (100 points) outrank classes (10 points). Inline styles override both, but using classes promotes flexibility and scalability.

Still so complicated?

Think of id as your unique name (only one of you), and class as your role or group — many people can share the same role.

Summary
      • id is unique and used once per page.
      • class is reusable across elements.
      • IDs have higher specificity; use sparingly for maintainability.
      • Use classes for scalable, component-based design.
Similar questions
Guides
22 / 30