Trusted answers to developer questions

CSS class vs.​ id

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

In CSS, the class and id attributes are used to style different HTML elements. The decision of which attribute to use depends on the problem.

The following examples will go over the main differences between the two.

Differences

1. An id is a unique identifier

Once an id has been used to target an element, that id cannot be used to target any other element in the HTML document. This is not true for a class:

2. Only one id can be assigned per element

An element can only have one id. However​, it can have multiple classes associated with it.

3. id has higher priority

If an element gets conflicting commands from it’s class and id attributes, then it will go with the commands provided by the id.

Some use cases

If some elements need to have a consistent style (e.g., all the buttons on a webpage need to look the same) then using classes will be beneficial.

If there is a need to overwrite existing styles without altering the existing stylesheet, then ids will be a suitable choice.

RELATED TAGS

css
class
id
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?