CSS Specificity

CSS specificity is the measure which determines the style to be displayed to an element. If two selectors are assigned to an element, the one with the highest specificity would be the one used.

Specificity Hierarchy

When determining the magnitude of elements specificity, it could be a bit hard, one of the best ways to determine their power is to rank them in a hierarchy.

There are 4 main types of selectors that determine specificity, and they are listed in an ascending order:

Elements and Pseudo-elements

Selection with element tags are done using p, h1, section. Pseudo-elements like ::before and ::after are used for selection.

carbon.png

Class selector, Attribute selector and Pseudo-class selector

class selectors are .red, selecting elements using their attributes are done like [type="checkbox"], Pseudo-class selectors are :hover, :focus.

carbon (1).png

Id selector

Using an id tag or selector is done using the Pound(hash) symbol. (eg., #home, #about).

carbon (2).png

Inline Styles

These styling is done directly in the html element. It normally looks like this;
<p style="color: red">This is a red paragraph</p>

carbon (3).png

Specificity Calculation

To determine the style rules that would be displayed, the specificity can be calculated, let's use some points to determine the specificity of some elements.

We will be making use of a point system to get our results. They are as follows;

p = 1 point.

.paragraph = 10 points.

#paragraph = 100 points.

<p style="color: red"> = 1000points.

carbon (4).png

Conclusion

To get an accurate specificity value, you have to make use of the point system, the system can also be used when more than one selector type is used in selection.

And finally, due to the cascading nature of CSS, if a selector type is used on the same element, the one that appears last would be the one that would be displayed.