What is the difference between id and class in css
ID’s are unique
- Each element can have only one ID
- Each page can have only one element with that ID
When I was first learning this stuff, I heard over and over that you should only use ID’s once, but you can use classes over and over. It basically went in one ear and out the other because it sounded more like a good “rule of thumb” to me rather than something extremely important. If you are purely an HTML/CSS person, this attitude can persist because to you, they really don’t seem to do anything different.
Here is one: your code will not pass validation if you use the same ID on more than one element. Validation should be important to all of us, so that alone is a big one. We’ll go over more reasons for uniqueness as we go on.
Classes are not unique
- You can use the same class on multiple elements.
- You can use multiple classes on the same element.
Any styling information that needs to be applied to multiple objects on a page should be done with a class. Take for example a page with multiple “widgets”:
You can now use the class name “widget” as your hook to apply the same set of styling to each one of these. But what if you need one of them to be bigger than the other, but still share all the other attributes? Classes has you covered there, as you can apply more than one class:
<div class="widget big"></div>
No need to make a brand new class name here, just apply a new class right in the class attribute. These classes are space-delimited and most browsers support any number of them (actually, it’s more like thousands, but way more than you’ll ever need).