What is the difference between id and classes in CSS?

Hi everyone,

I am new to coding and would really appreciate any thoughts not this question.

Thank you!

Both are attributes you set on HTML elements, either by writing them in your HTML or by setting them programmatically with JavaScript. Both allow you to select or target an element in your CSS. The primary difference is that classes are meant to be reused throughout a page, whereas an ID is meant to be unique to one element.

An example class may be “red-border”. Then you could write

.red-border {
  border: 1px solid red;

in your css and any element with the red-border class would get that rule applied. An element can also have multiple classes, for example:

<div class="red-border yellow-background width-100"></div>

Conversely, an element should only have one id, and it should be the only element on the page with that id.

P.S. Don’t forget to search the web when you have a coding question. A quick search for me turned up:


One main difference between the two is in their specificity. ID’s have a much higher specificity than Classes which means that an ID will “overwrite” a class. For example:

#color {
background-color: red; }

.background {
background-color: blue; }

If both of those were classes then the background-color would be blue because that statement came after the previous, however because the first one is an ID it will take precedence over the class regardless of its position.

Edit: I’m still a newbie here so if I made any errors please let me know.

1 Like