What is the difference between ID and class?


#1

i don't really understand the difference between the two of them. It says that you can apply a class to lots of things, but ID to only one element, but that's not true because I applied the ID "intro" to two things, and it worked, the css properties i had set for intro worked on two different elements. So what's teh difference between the two?


#2

If I am correct, an ID identifies something while classes are a section of certain IDs in which are under a class. Think like this. In a RPG there are classes, knights, mages, etc. and there are people that are those like a knight or mage. So if you set an ID to an element, you can list it's ID and Element Under a Class. However, I am probably wrong because I know very little of any coding languages.


#3

there is this great question on stackoverflow, which answers your question in detail


#4

Like @austiepie123 said, the easiest way to put it is like this:

a class is a type, so it's like knight, archer or mage, and id is the specific knight archer or mage, so it could be Sir Lancelot.

Classes are generally used for multiple things, like I said, if you want some knights, it's class, and you would give this class to all of the knights, whereas id is only for one specific thing, e.g. Sir Lancelot.


#5

Apart from understanding the differences between Class and ID in CSS - you have to think about specificity and cleanliness of your code as well.

Once you start adding IDs to everything, it gets messy real quick. IDs should be reserved for special purposes, unique items. Classes are better for targeting multiple items at the same time.

Just to clarify a bit futher, each element can have only one ID and each page can have only one element with that ID. As for classes, you can use the same class on multiple elements and you can use multiple classes on the same element. When you make a change to that class, it's applied to all elements with that class.

Hope this helps too!

Resource Smashing Magazine has this cool breakdown of what specificity is.


#6

Wow, i had no idea there was such a complicated system behind it. I think the concept is pretty easy to grasp, just to remember the combination is tricky. I just compare it with linux permission, but slightly different


#7

I had the same question. I found this article which I found explained very well the difference in how they are used.
https://css-tricks.com/the-difference-between-id-and-class/


#8

I might have missed it, but ids are stronger then classes, if we have this:

<p id="red" class="blue">i am red</p>

and then css;

#red { color: red; }
.blue { color: blue; }

the text will be red, not blue


#9

Yeah that's because IDs are specific, an ID is just one so if you have a class that says all .boxes are are blue, then give one .box an ID of #red that makes it red, it will be red.

Basically put, ID does override Class.