CSS specifity

Mario Code , , ,
0

Did you sometimes ask yourself “Why does this style show up in the browser and not the other one?” Sometimes exploding into a “WTF??!!”

And after that out of pure despair you took the last exit with !important….it worked…but, damn that just doesn’t feel right.

This was sure because of the specifity of css styles (from hell ;-)).

CSS Specifity point system

Different DOM elements have a different specifity. To explain it better i show it with a point system. Elements with higher specifity get more points and elements with lesser specifity…uhm, you get the idea.

The Element/style/css-rule with the most points will be shown in the browser.

A tag gets only 1 point:
div {background-color: grey;}

pseudo classes own 10 points:
a:first-child

A class shows up with 100 points:
.test {background-color: green;}

The ID comes with a bulk of 1,000 points:
#message {background-color: yellow;}

An in-element-style arrives with a whooping 10,000 points
<div style="background-color: red"></div>

And the alltime favorite !important hits your styles with an allmighty 100,000 points!

A little overview:

HTML/CSSSpecifity/Points
HTML-Elementes (Tags)1
:pseudo10
.class100
#ID1.000
In-Element10.000
!important100.000

Addition of CSS specifities

Depending on how you write your styles the specifities/points add up.
A few examples:

Tag/CSSSpecifity/Points
a1
ul li2 ( 1 + 1 )
div:empty11 ( 1 + 10 )
div.mdodiv101 ( 1 + 100 )
div#mdodiv1.001 ( 1 + 1.000 )
div#mdodiv !important101.001 ( 1 + 1.000 + 100.000 )

Especially regarding to specifities, it is essentially necessary to keep an eye on how you write your styles.
Why? Let’s see. If you write div#mdodiv with a space div #mdodiv it gets a totally different meaning, specifity and changes the addition of the points.

div#mdodiv “add the style to the DIV which does have the ID=mdodiv”
div #mdodiv “add this style to all elements whose ID=mdodiv and are surrounded by a DIV”

A small difference with a big impact!

I prepared a few codepens with which you can play around to get a better feeling for the specifities and additions.

ul li => 2

See the Pen CSS specifity example 0.5 by Mario Domandl (@mdo-code) on CodePen.

div:empty => 11

See the Pen CSS specifity example 1 by Mario Domandl (@mdo-code) on CodePen.

div.mdodiv => 101

See the Pen CSS specifity example 2 by Mario Domandl (@mdo-code) on CodePen.

div#mdodiv => 1001

See the Pen CSS specifity example 3 by Mario Domandl (@mdo-code) on CodePen.

inline Style

See the Pen CSS specifity example 4 by Mario Domandl (@mdo-code) on CodePen.

!important

See the Pen CSS specifity example 5 by Mario Domandl (@mdo-code) on CodePen.

!important Addition

See the Pen CSS specifity example 6 by Mario Domandl (@mdo-code) on CodePen.

Always keep an eye on your writing!

See the Pen CSS specifity example 7 by Mario Domandl (@mdo-code) on CodePen.

 

Leave a Reply