chevron_left
399 points
8 4 3

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”:

<div class="widget"></div>
<div class="widget"></div>
<div class="widget"></div>

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"></div>
<div class="widget big"></div>
<div class="widget"></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).

More Posts

Difference between class and id attribute in html Sanjana Sagar - May 28
What is the difference between classes and ids in CSS? Hafsa_Rao - Jul 9
Difference between class and method in java Sanjana Sagar - May 20
What is the difference between abstraction and encapsulation in java Sanjana Sagar - May 20
What is the difference between a class and an interface mhfaisal - Jun 12
What is the difference between ascii and unicode Sanjana Sagar - May 28
What is the difference between thread and process Sanjana Sagar - May 28
What is the difference between a stack and a queue Sanjana Sagar - May 28
What is the difference between varchar and nvarchar Sanjana Sagar - May 22
What is the difference between pre and post Sanjana Sagar - May 20