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 -

And the HTML code would look like this -

This is the final output -

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 -
- A class name can be used by multiple elements
- Each element can have multiple classes.
- An ID on the other hand, can only be used by one element
- Each element can only have one id.
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 -
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! 😁