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
- special-header
- highlight
- a_108
- BIG:test.example
- kitten🐈
Invalid ID examples (Don't use these!)
Invalid ID | Reason |
---|---|
3col | |
_note | |
🤪silly |
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
- special
- login__button--primary
- Merch_Heading
- shadow9
Invalid class examples (Don't use these!)
Invalid Class | Reason |
---|---|
12column | |
:marked | |
🤭no |
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:
- Replace Divs With Custom Elements For Superior Markup
- Custom HTML Tags (18 Things To Know Before Using Them)
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
- Use IDs for single elements on the page.
- Use classes for multiple elements on a page.
- Use existing attributes instead of adding IDs or classes if you can.
- Use custom elements instead of divs (with IDs or classes) for cleaner code.
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).
“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 — 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.
Jasper — Best Content Creation Tool
Plan, outline, and write long-form website articles with the power of AI and produce content faster than ever.
Canva — Best Graphic Design Software
Create professional graphics and social media imagery with an intuitive online interface.
SiteGround — Best Website Hosting
Professional Wordpress hosting with 24/7 customer support that is the best in the industry, hands down!
See more of my recommended dev tools.