ID's differ from classes in that they are used for a few different things. Firstly, they are unique! Each ID can only be used on one element, unlike classes that can be used on multiple.
An example of the ID attribute being used. Note how the ID's are not used multiple times.
Secondly, they can be used to target certain parts of the page so you can navigate around easier. This looks exactly the same in the code as when you would style it. If you want an example of this, inspect the element of this page and you will see the top of the page is targetted by an ID!
A class is composed of two parts. One part HTML and one part CSS.
In html, class is an attribute which is assigned to an element. Many classes can be assigned to one element and many elements can share a class. This is a feature of classes that differs from ID.
An example of the class attribute being applied to multiple elements in HTML.
In CSS, class is used as a selector to be targetted by the CSS to style the element the class is attached to. We use the format .example to select class attributes with our CSS. We then use rules within our {} to apply to our elements that have classes on them. We can even target multiple classes at the same time!
An example of the class selector being used in CSS to target one and multiple classes at the same time.
The best practice for using class and ID is that you want to use classes when you want to apply a style to multiple elements. You use ID when you only want a style to apply to a single element. You can apply both a class and an ID to an element, just remember that the ID will override the class if they are doing the same type of styling. (color for instance).
Back to Top