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.
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
.
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.
Free Resources