i

Learn HTML and CSS in 10 Days

Calculating Specificity

Every selector used in CSS has its specific weight. A selector's placement and weight in the cascade determines how its style should get rendered.

In the 1st Chapter, we talked about 3 kinds of selectors: type, class and ID selectors. Each of them comes with different specificity weight. 

The type selector comes with the least specificity weight with a point value of 0-0-1. The class selector comes with medium specificity weight with a point value of 0-1-0. The highest specificity weight is of ID selector with a point value of 1-0-0. We can see here that the specificity points gets determined by utilizing three columns. The 1st column counts ID selectors, the 2nd one counts Class selectors, and the 3rd one counts Type selectors.

Whenever there is a styling conflict, then the selector with a higher specificity weight is said to be more superior. Suppose at one place a paragraph is chosen using a Type selector, and at the second instance, a paragraph is selected using an ID selector. As the ID selector has more specificity value, it will take the precedence regardless of the cascade.

Let's take an example of that.

 The HTML code contains a paragraph element with 'food' as the id attribute value. In our CSS code, the paragraph is selected using two kinds of selectors, one is the Type, and the other is the ID selector. Though the Type selector comes after the ID selector, the ID selector outweighs the Type selector since it has a higher specificity weight and the paragraph will get displayed with the green background.

We need to remember the specificity weight of different selectors. It may happen that the CSS code is not giving up the desired styling. The reason for the break in the cascade may be due to the specificity weight.

Seeing how the specificity and cascade work is a tremendous obstacle, and we'll keep on covering this subject. But for now, let's see how can we be more intentional and particular with our selectors by combining them.