Classes vs ID's

First of all, what are Classes/ID's?

Classes and ID's are two awesome features of CSS. Instead of having to manually style each and every HTML element, classes allow us to abstract out the styling of a feature and reuse it throughout the project. ID's on the other hand, also allow us to abstract out the styling of a feature in a project. Generally, best practice is to use classes for elements that will appear multiple times throughout a webpage and ID's should be used only for one element. Some key reasons for that are as follows:

  1. ID's can be adjusted via JavaScript
  2. ID's have a higher priority in the DOM than classes.

Why do these matter?

If we choose to add JavaScript functionality to our element, having it appear multiple times throughout a webpage cause issues with the functionality of it and just causes unnecessary headache.

Since ID's have a higher priority than classes, it is better to use classes for the general case. When wanting to control a specific element, we can then use ID's to override any pre-set conditions from the class.

How to Implement a classes and ID's together in CSS

So, with that out of the way, how do we implement our class in CSS?

First, we add a class entry into the CSS file, with the associated element properties that we want. We signify that it's a class by prepending the entry with a '.' symbol. After that, we simply assign the class to the element via its class property inside .html file, as shown below.

main.css

.blog-img {
    max-width: 30%;
    border-radius: 5px;
    height: auto;
    justify-content: center;
}

classes-vs-ids.html

<img src="/blog/images/pup10.jpg" class="blog-img">

Here, we can see how our image will appear after being given the class assignment.

Now, let's say we want to show three images, with similar properties but we want one to stand out. We can achieve this, by using the heightened priority property of ID's. To create an ID, it's the same as creating a class, however we prepend the name of it with a '#' symbol instead of a '.' symbol and we call assign the id in the element's id property rather than the class property, as shown below.

Now, let's see it in action when used below:

You can see, by using ID's for specific objects, and classes for general elements we are able to easily manipulate a single object.

Return to Home