Matthew James Taylor Matthew James Taylor

Web design ›

ID vs Class: Which CSS Selector Should You Use? (6 Examples)

30 Jan 2023

Table of contents

There are many ways to target an element in CSS, but which selector is best?

The ID attribute is used to uniquely identify a single element within a web page, while the class attribute is used to apply styles to multiple elements with the same class name. ID elements can only appear once per page, while multiple elements can have the same class.

ID Class
Once per page Multiple times per page
<div id="tag"> <div class="tag">
Pound (#) Period (.)
#tag {} .tag {}

In this article, I will showcase the pros and cons of ID and class selectors so you can determine which is best for your situation.

I will also introduce some interesting alternatives that you may not be aware of.

ID Selector

The ID selector targets a single element within an HTML document with the specified ID attribute and applies styles to it. Each unique ID can only be used for one element per page.

HTML example

Here's a div with an ID of 'special':

<div id="special">Text</div>

CSS example

To specify an ID selector in CSS you prefix the ID name with the pound symbol (#):

#special {
    /* style rules here */
}

Valid ID values

IDs must start with an ASCII letter (a-z or A-Z) and can be followed by any number of letters, numbers (0-9), hyphens (-), underscores (_), colons (:), periods (.), or emojis (🐶).

Valid ID examples

Invalid ID examples (Don't use these!)

Invalid ID Reason
3col IDs cannot start with a number
_note IDs cannot start with hyphens (-), underscores (_), colons (:), or periods (.)
🤪silly IDs cannot start with an emoji character

IDs must be unique per page

It is invalid HTML to use the same ID on multiple elements within a single HTML document.

If you have multiple, identical IDs, browsers may gracefully apply styles to all matches but this is not to be relied on. An in-page anchor (using the pound URL suffix) will only scroll down to the first occurrence of the ID, eg: example.com/page-name#anchor-name

Specificity

ID selectors have a specificity of 0,1,0,0 so they will take precedence over class selectors.

Selecting elements with an ID in javascript

When it comes to javascript, IDs are superior to classes because they are so much easier to work with.

Here's how easy it is to get an element with a specific ID in javascript:

element = document.getElementById('special');

When to use the ID selector

The ID selector is best to use when you are styling a single element on the page and it is not likely that the same styles will need to be applied to other page elements in the future.

Class Selector

The class selector targets all elements within an HTML document with the specified class attribute and applies styles to them. The same class can be used on multiple elements.

HTML example

Here is a div with a class of 'special':

<div class="special">Text</div>

CSS example

To specify a class selector in CSS you prefix the class name with a period:

.special {
    /* style rules here */
}

Valid class names

Class names must start with an ASCII letter (a-z or A-Z), hyphen (-), or underscore (_), and can be followed by any number of letters, numbers (0-9), hyphens (-), underscores (_), colons (:), periods (.), or emojis (🐶).

Valid class examples

Invalid class examples (Don't use these!)

Invalid Class Reason
12column Classes cannot start with a number
:marked Classes cannot start with colons (:), or periods (.)
🤭no Classes cannot start with an emoji character

Specificity

Class selectors have a specificity of 0,0,1,0 so they will be overruled by the higher specificity of ID selectors.

Selecting elements with a class in javascript

Classes can be applied to multiple elements within a page so in javascript you need to retrieve a list of matching elements and then loop through them.

Here's one way to do this:

Array.prototype.forEach.call(document.querySelectorAll('.special'), function(el) {
    /* do something with each element (el) */
});

When to use the class selector

Class selectors are best to use when the styles apply to multiple elements on a single web page.

Alternatives To ID and Class

Sometimes an ID or class is not the best option because there is already a way to select your target element(s).

Use an existing attribute as the CSS selector

If the element you are trying to target already has a unique attribute then you can use this instead of adding an ID.

Here are two examples

1. Use link href values as selectors

Let's imagine you have this menu:

<nav>
    <a href="/">Home</a>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
</nav>

You can select your home link by using an attribute selector in combination with element selectors:

nav a[href="/"] {
    /* style rules here */
}

2. Use Aria labels as selectors

Imagine you have a set of social links and you're using SVG images for the icons. There is no readable text component for these links, so for accessibility, you need to add aria labels so screen readers have a description.

Here's what that looks like:

<div id="social">
    <a aria-label="Twitter" href="https://twitter.com"><svg ... ></a>
    <a aria-label="Instagram" href="https://www.instagram.com"><svg ... ></a>
</div>

You can select individual social links by their unique aria-label:

#social a[aria-label="Twitter"] {
    /* style rules here */
}

Attribute selector specificity

Attribute selectors have the same specificity as classes (0,0,1,0) so they can be used interchangeably without affecting the overall specificity.

Use a unique tag as the CSS selector

Some HTML elements are only allowed to be used once per page, eg: <main>, and <h1>.

With only one of these elements guaranteed per page, it's safe to select them with a simple element selector:

main {
    /* style rules here */
}

h1 {
    /* style rules here */
}

IDs or classes are just not necessary in this situation.

Element selector specificity

Element selectors (tags) have the lowest specificity (0,0,0,1) so they will be overruled by IDs, classes, and attributes.

Use a custom element as the CSS selector

If you're adding IDs or classes to a <div> then it may be better to use a custom element.

Instead of:

<div class="details-panel"></div>

Make your own custom element:

<details-panel></details-panel>

And target it in CSS the same way as the element selector:

details-panel {
    /* style rules here */
}

Custom elements are 100% valid HTML, they work in all browsers, are more semantic than divs, are more readable, shorter, and overall create a better developer experience.

Read more about custom elements in my articles:

Custom element selector specificity

Custom element selectors have the same specificity as element selectors (0,0,0,1) so they will be overruled by IDs, classes, and attributes.

In Summary

Do you know how HTML and CSS go together? See my beginners guide: How to add CSS to HTML (With Link, Embed, Import, and Inline styles).

Matthew James Taylor

“I've been developing websites professionally for over two decades and running this site since 1997! During this time I've found many amazing tools and services that I cannot live without.”
— Matthew James Taylor

I highly Recommend:

Ezoic

Ezoic — Best ad network for publishers

Earn more than double the revenue of Google Adsense. It's easy to set up and there's no minimum traffic requirements.

Learn more

Jasper

Jasper — Best Content Creation Tool

Plan, outline, and write long-form website articles with the power of AI and produce content faster than ever.

Learn more

Canva

Canva — Best Graphic Design Software

Create professional graphics and social media imagery with an intuitive online interface.

Learn more

SiteGround

SiteGround — Best Website Hosting

Professional Wordpress hosting with 24/7 customer support that is the best in the industry, hands down!

Learn more

See more of my recommended dev tools.

Responsive Columns Layout System

Responsive Columns: Build Amazing Layouts With Custom HTML Tags

How responsive attributes work

Responsive Attributes: Generate CSS Grid Layouts With Simple HTML

Responsive text size

Responsive Font Size (Optimal Text at Every Breakpoint)

A web developer in the engine room

Best Web Development Tools (Free & Paid)

Columns all the same height

Equal-Height Columns (CSS Grid, Flexbox, Floated Containers, & Table Methods)

Boggle dice shaker

Boggle Dice Shaker (Built With Javascript)

Padding bewteen desktop, tablet, and mobile

Responsive Padding, Margin & Gutters With CSS Calc

Holy grail 3 column layout responsive diagram

Holy Grail 3-Column Responsive Layout (CSS Grid & Flexbox Versions)

Footer at the bottom of the page diagram

Bottom Footer (CSS Grid, Flexbox, & Absolute Position Methods)

3 column product comparison layout

3 Column Layouts (Responsive, Flexbox & CSS Grid)

Open book two column layout

2 Column Layouts (Responsive, Flexbox & CSS Grid)

Is CSS margin top or bottom better?

CSS: Margin Top vs Bottom (A Trick You Should Know)

How to add CSS to HTML

How to add CSS to HTML (With Link, Embed, Import, and Inline styles)

Custom elements plus CSS with no javascript

Custom Element Examples (Without Javascript)

A delicious soup made from custom elements

Replace Divs With Custom Elements For Superior Markup

Racing car made from custom tags

Custom HTML Tags (18 Things To Know Before Using Them)

Looking into an empty div

Empty HTML Tags (21 Weird Things You Need To Know!)

Beautiful centered menus with CSS

CSS: Horizontally Centred Menus (With Optional Dropdowns)

Ads that can change size to fit any screen size

Responsive Banner Ads with HTML5 and CSS3

Superman blocking styles

Style Blocker: How To Prevent CSS Cascade With Shadow DOM

Responsive house plan

Responsive House Plan (Web Design Meets Architecture!)

Web design Web design Architecture Architecture Life drawing Life drawing Art gallery Art gallery Synesthesia Synesthesia Comics Comics

About Contact Privacy

© 1994 — 2024 Matthew James Taylor