TIL: CSS Selector Specificity

Today I’ve read a post from the code miner blog talking about CSS specificity. CSS Selector Specificity It’s a way of avoiding the use of !import directive and it’s quite simple:

Suppose that you have a CSS like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
div {
    background-color: white;
}

#box {
    background-color: red;
}

.box {
    background-color: black;
}

and this css code is applied to a HTML like this:

1
<div id="box" class=".box">
The question is: “What will be the background color of that div?

The answer is the result of specificity calculation and it’s like this:

!importantstyle attributesidClass, Attribute selector, pseudo-classesTag, pseudo-elements
!import#id.class,[type=“input”],:hoverh1, ::before

The table of points will be:

selector!importantstyle attributesidClass, Attribute selector, pseudo-classesType, pseudo-elements
div00001
#box00100
.box00010

The biggest value we got is #box, which is 00100. And the background color will be red!

More examples can be found on the original post: https://blog.codeminer42.com/codetips2-how-specificity-works-in-css/