You may have heard about these things on the web. You have probably seen them in your code. It looks very familiar:
It doesn’t need to be confusing. Classes and IDs are simply a way to organize your code and add styles to certain elements in your design. To make it easier to understand, think of it like this: Classes are little children, and ID’s are parents. There is only one parent, but there can be many children. Also, Parents have more authority than children.
In CSS, classes have a period before them and look like .box1. You style them like any other element. However, you can have more than one of these on a page. So you can have <div> tags throughout your page and style them the same by giving them the same class.
ID’s are more strict. They have a pound sign before them (#), and you can only have one ID name throughout your page. For example, only one element on your page can have an ID of “nav”.
The both do the same thing, so how do you know when to use them? There’s no set rule, but since a particular ID can only be assigned to one element, if you want a style that will applied to many elements, then you may want to group it into a class. In my CSS, I have some standard classes that do basic styling. For example, I have a class called “alignleft”, that has the styles: “float: left;” and “margin-right: 10px”. Anytime I want to put an image on the left side of the page, I just need to give that element a class of “alignleft”.
Next time, I’ll talk about the best practices of using Classes. Stay tuned!