ID's versus Classes: The Breakdown

How to use your HTML tags wisely

January 25th, 2015 : 5 minutes

If you have many things that need the same styling, you should use a class. This way you can save yourself the time and trouble of applying the same rules to several selectors. How about this example: I am making a website. I want to have icons that link to my different social media sites. Facebook, Twitter, and LinkedIn. I want all three of my icons to be sized in the same way but for some reason, my Facebook icon is a little bigger that the other two.

So I think ID's are easier to understand, so I'm going to start there. You have a million images or div's and you want to call on a specific one in your CSS file. Giving one a special ID badge makes it easy to do that. So let's see how you would use ID's for the example I described above:

I have three different div's, each with their own ID. So the thing to remember is that IDs are unique. Any one element can only have one ID, and each page can have only one element that has that ID.

So this is what you would maybe see in your CSS file.

Okay, so how could do go abou this a different way using classes? Classes are not unique; they are general. You can use the same class on multiple elements on the same page and you can use multiple classes on the same element.

See the HTML below:

I replaced all of the unique ID's with a class ("social-media-icon"). This way I don't have to repeat the same properties for each icon. (Yay!) Do note that I left the ID for the Facebook icon, because I still want to adjust that image specifically without touching any other image.

If you can imagine having hundreds of different elements (rather than just three) you can see why it would be wise to use a class rather than many IDs.