i

Learn HTML and CSS in 10 Days

Layering Styles With Multiple Classes

One of the most popular methods to keep the selector's specificity weight low is to be as much modular as possible. And the best way to be modular is by layering using multiple classes.

HTML's elements can come with more than one Class attribute value, but a space separates each of them. With that, we can put certain styles on all elements of one sort while putting different styles just on the explicit element of that sort. We can attach styles we need to continually reuse to one class and layer on extra styles from another class.

Let's understand the above case with an example. Suppose we want that all our buttons present in the web page should have a font size of 16 pixels, but at the same time, we also wish that the colour of the background of our button should vary depending on the locations. Thus we can make a couple of classes and then layer them up on elements as per the requirement to get the desired result.

CSS

.btn {

font-size: 16px;

}

.btn-danger {

background: red;

}

.btn-success {

background: green;

}

In the above code, you can get two anchor elements with different class attribute values. The first one, i.e. 'btn', is utilized in providing the font size of 16 pixels to each element. The 1st anchor also has an additional class value of 'btn-danger' which gives red colour in the background of the button. On the other hand, the second class has an additional class value of 'btn success' which offers a green background colour. Thus the styles here are modular and clean.

Thus if you want to keep your code lean and want a low specificity weight, then use multiple classes along with the layering of elements. Much like determining the specificity and knowing cascade, this practice also takes time to be fully confident into it. But don’t worry, with each chapter you will be getting that.