What are the best practices associated with using classes vs. IDs?

class vs ID logo

When I started my journey on becoming a web developer, I knew very little about HTML classes and probably even less about ID’s, and though I am not at all an expert on the matter I feel as though I am learning a thing or two. So, in this blog entry I will talk a little bit about what class’s and ID’s are and some of the practices to keep in mind.

One analogy that helped me understand ID’s and classes better is the barcode and serial number analogy. Take an iPhone in a store for instance, the iPod has a barcode which the store can scan and retrieve some information about the iPhone. The barcode knows exactly what the products is, what it costs and it might even know the color. All iPhones of this type have the exact same barcode on them.

The iPhone will also have a serial number on it which is completely unique to any other iPhone in the world. The serial number does not know the cost of the iPhone as this will vary from place to place. Now you can make the system learn the price through the serial number, however this is not a very efficient way of storing data. If the price changes you will need to change this information for every single serial numbers. Therefore, it is much easier to use the barcode as you would be able to just change the price for every product with that barcode.

This is much like ID’s and Classes. Information that is reusable should be kept in a class and information that is totally unique should be kept in an ID.

ID Selector:

Best practice for ID’s is that they are unique and that each element can only have one ID and each page should only have one element with that ID. To assign an ID in HTML we use ID=’id_name’, and to customize an ID in CSS we use #id_name{}.

ID example

Class Selector:

Best practice for Classes is that they don’t have to be unique and you can use the same class on multiple elements and you can use multiple classes on the same element. To assign a Class in HTML we use class=’class_name’, and to customize a Class in CSS we use .class_name{}.

Class example

Make 'em count:

Always make sure that when you are using a class or an ID to make sure that the name you are giving them is descriptive. This will help with the future proofing of your work as it will be easier for you to distinguish between variables.