Home About Me Blog Music

Classes vs Ids

This blog will tell you a little bit about classes and ids and about the best practices in using them.

11 Feb 2021

Classes and id's are two types of selectors. We define them and give them a function in CSS and then assign them to our HTML elements to make the elements more specific.

In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”)

So the CSS would look something like this -

Picture of CSS code

And the HTML code would look like this -

Picture of html code

This is the final output -

Picture of html code

Both these do pretty much the same thing, you target an element specifically and then manipulate it to be different from other elements.

But then "why have both?", you may ask.......I will tell you.

The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one. Important things to remember -

So now, what are the best practices?

I've already mentioned the most important rule: make your ids unique but assign your classes to as many elements as you want. Having said that; if you don't need them, don't use them. Avoid things like this -

Picture of html code

We can see that this is an anchor element and it is a link. We don't need to apply a class because we can easily just add styling via its tag. Other HTML tags that we can target directly are paragraph tags and header tags. Only if you need to individually style them (for example a title) does it make sense to give them another selector.

Also, when you create classes or Ids, you should make them descriptive but keep it as short as possible. Instead of calling a class/id "top navigation bar" just use "topnav".

Hope that helped in understanding classes and id's a bit more. And stay tuned for more posts...

Have an awesome day! 😁