XenonStack

Service Design

XenonStack Insights Class vs ID Selector in CSS: Differences and Rules

and | Published | Updated

Class vs ID Selector in CSS: Differences and Rules
7:11
Class vs ID selector in CSS: syntax, rules and specificity, from valid HTML attributes up to maintainable stylesheets

Key takeaway

  • Class vs ID selector in CSS: syntax, naming rules, specificity and when to use each, with a comparison table and tips for maintainable stylesheets.

A class selector (.name) matches every element whose class attribute contains that name, so one rule can style a whole group. An ID selector (#name) matches the one element whose id attribute has that value, and the value must be unique in the document. Use classes for styling and reuse, and keep IDs for anchors, labels and script hooks.

The practical difference is weight. According to MDN, one ID selector outranks any number of class selectors, which is why IDs make stylesheets hard to override. The sections below cover the syntax, the naming rules, the specificity arithmetic and the habits that keep CSS maintainable across teams.

What is the difference between a class and an ID selector?

PointClass selectorID selector
Syntax.card { }#header { }
MatchesEvery element with that class in its class listThe element whose id equals the value
UniquenessReusable on any number of elementsThe value must be unique within the document
Per elementAn element can carry several classes, separated by spacesAn element has one id, and it cannot contain whitespace
Specificity0-1-01-0-0
Equivalent attribute selector[class~="card"][id="header"] (same match, lower specificity)
Best used forStyling and reusable componentsFragment links, form labels, script hooks

Sources: MDN pages on class selectors, ID selectors and specificity, read 13 November 2026.

Two-column comparison of class and ID selectors covering syntax, reach, per-element rules and specificity, ending with the rule to style with classes and keep IDs for anchors and script hooks

How does a class selector work?

A class selector starts with a full stop followed by the class name. The browser applies the rule to every element whose class attribute lists that name. The class attribute holds a list of names separated by whitespace, so one element can take several classes, as MDN describes.

/* one rule, many elements */
.note { border-left: 4px solid #2a5bd7; }

/* an element must carry both classes */
li.spacious.elegant { margin: 2em; }

Chaining classes with no space between them requires all of them on the same element. A space changes the meaning: .red.fancy matches one element with both classes, while .red .fancy matches a .fancy element inside a .red element.

Naming rules for classes

  • Class values may contain any character except ASCII whitespace, but a name used in a selector must be a valid CSS identifier. A name such as 123item or item?one must be escaped in the selector, for example .\31 23item, or the rule is ignored.
  • MDN recommends names that describe purpose, such as warning, rather than appearance, such as red-text, so the name stays correct if the design changes.

How does an ID selector work?

An ID selector starts with a hash character followed by the value of the id attribute. It matches the element with that exact value.

#site-header { position: sticky; top: 0; }

Rules for ID values

  • The value must be unique within the whole document, and an element has only one.
  • It must not contain whitespace. Unlike class, an id cannot hold a list.
  • Technically it can contain any Unicode character, but for use in CSS or querySelector() it must be a valid CSS identifier. Otherwise escape it with CSS.escape(). MDN recommends choosing values that need no escaping. Source: MDN, the id attribute.

A common convention is to start IDs and class names with a letter and use only letters, digits, hyphens and underscores. This is stricter than HTML requires, but such names need no escaping in selectors.

Where are classes and IDs used besides styling?

UseClassID
StylingPreferred for almost all rulesPossible, but carries high specificity
Fragment linksNot applicable<a href="#exciting"> jumps to the element with id="exciting"
JavaScript lookupdocument.getElementsByClassName("note"), querySelectorAll(".note")document.getElementById("exciting"), querySelector("#exciting")
Changing stateelement.classList.add("active") or toggleNot used for state

MDN advises against reading IDs as properties of window, because they can collide with existing or future browser globals. Use getElementById() or querySelector() instead. The method is getElementsByClassName, with an s, and it returns a live collection.

Which selector wins when both apply?

Specificity is a three-column value, ID then class then type. MDN lists what counts in each column: ID selectors in the first, class selectors, attribute selectors and pseudo-classes in the second, and type selectors and pseudo-elements in the third. Columns are compared left to right, so one ID beats any number of classes. If all three tie, the rule declared last wins.

#panel { color: green; }          /* 1-0-0, wins */
.a .b .c .d { color: yellow; }   /* 0-4-0 */
SituationWhat MDN says
Inline style attributeBeats normal author rules; only !important overrides it
!importantOverrides specificity within the same origin and layer, and MDN calls using it to win specificity fights a bad practice
:where()Always adds 0-0-0, useful for low-specificity base styles
:is(), :not(), :has()Add nothing themselves, but their most specific argument counts
Cascade layers (@layer)Later layers win without specificity tricks; unlayered styles beat layered ones from the same origin

Source: MDN, specificity, read 13 November 2026.

When should you use a class and when an ID?

NeedChooseWhy
Style a component used more than onceClassReusable and low specificity
Style one element in a shared stylesheetClassAvoids a high-specificity rule that later rules must fight
Link to a section of the pageIDA fragment link needs an element with that id
Associate a form label with a fieldIDThe for attribute refers to an id
Reach one element from a scriptID or classgetElementById is direct; a data attribute or class also works
Override a third-party styleClass, then layersPrefer cascade layers or :where() over IDs and !important

Which habits keep large stylesheets maintainable?

  • Style with classes and keep specificity low, so later rules can override earlier ones without escalation.
  • Keep IDs for anchors, labels and script hooks, and keep them unique. Duplicate IDs are invalid and make lookups unreliable.
  • Name classes by purpose, not appearance.
  • Use classList to change state in scripts, not inline styles, so the stylesheet stays the single source of styling.
  • Reach for cascade layers or :where() before !important.

Related reading on CSS: CSS content-visibility, CSS animation keyframes, fluid typography with clamp() and CSS mask and clip-path. If you work in React, see functional vs class components, which concerns a different meaning of "class".

Why does this matter beyond one stylesheet?

For engineering leads, selector rules are a small part of a delivery standard: shared naming conventions, low specificity and review checks keep front-end code easy to change across teams. The same idea of written conventions that are enforced, not remembered, applies when teams build agent workflows. ElixirClaw is an agentic OS platform to build, orchestrate and govern AI agents and automation workflows while keeping humans in control.

To map one engineering decision your agents should make, and the context and policy it depends on, book a Context Workshop. See what happens in the workshop.

Frequently asked questions

What is the main difference between a class and an ID in CSS?

A class can be applied to many elements and an element can have several classes. An ID must be unique in the document, and an element has one. A class selector starts with a full stop and an ID selector with a hash.

Can two elements share the same ID?

No. The id value must be unique within the document. Duplicate IDs are invalid HTML, so use a class when more than one element needs the same styling.

Can an element have more than one class?

Yes. The class attribute is a list of names separated by whitespace, and a selector such as li.spacious.elegant matches only elements that carry both.

Which has higher specificity, a class or an ID?

An ID. Specificity is compared ID first, then class, then type, so one ID selector (1-0-0) outranks any number of class selectors (0-1-0 each), according to MDN.

Should I avoid ID selectors in CSS?

For styling, mostly yes, because their high specificity makes rules hard to override. IDs remain the right choice for fragment links, label associations and script hooks.

What is the correct JavaScript method to find elements by class?

document.getElementsByClassName("name") or querySelectorAll(".name"). For an ID use getElementById("name") or querySelector("#name").

Table of Contents

navdeep-singh-gill

Navdeep Singh Gill

Global CEO and Founder of XenonStack

LinkedIn profile

Navdeep Singh Gill is serving as Chief Executive Officer and Product Architect at XenonStack. He holds expertise in building SaaS Platform for Decentralised Big Data management and Governance, AI Marketplace for Operationalising and Scaling. His incredible experience in AI Technologies and Big Data Engineering thrills him to write about different use cases and its approach to solutions.

Get the latest articles in your inbox

Subscribe Now

Interested in Solving your Challenges with XenonStack Team
Get Started

Get Started with your requirements and primary focus, that will help us to make your solution

Please Select your Industry
Banking
Fintech
Payment Providers
Wealth Management
Discrete Manufacturing
Semiconductor
Machinery Manufacturing / Automation
Appliances / Electrical / Electronics
Elevator Manufacturing
Defense & Space Manufacturing
Computers & Electronics / Industrial Machinery
Motor Vehicle Manufacturing
Food and Beverages
Distillery & Wines
Beverages
Shipping
Logistics
Mobility (EV / Public Transport)
Energy & Utilities
Hospitality
Digital Gaming Platforms
SportsTech with AI
Public Safety - Explosives
Public Safety - Firefighting
Public Safety - Surveillance
Public Safety - Others
Media Platforms
City Operations
Airlines & Aviation
Defense Warfare & Drones
Robotics Engineering
Drones Manufacturing
AI Labs for Colleges
AI MSP / Quantum / AGI Institutes
Retail Apparel and Fashion

Proceed Next