Extra – Priority of CSS selectors

CSS stands for Cascading Style sheets. Where cascading means the same element may be affected by multiple rules.

That’s all fine when multiple rules for the same element apply different properties.

But what happens when different rules are defining the same property? Which one is applied? Here comes the priority formula.

The most priority one is !important. But be careful when using it.

1body {
2  color: red !important;
3}

Otherwise, it is the selector combination to determine the priority.

!important style   id   class   tag

   A         B      C      D     E
1<div>Hello CSS</div>
2<div id='target1' class='important'>Target 1: Hello CSS</div>
3<div id='target2' class='important'>Target 2: Hello CSS</div>
4<div id='target3' class='important'>Target 3: Hello CSS</div>
5<div id='target4' class='important' style='color:black'>Target 4: Hello CSS</div>
 1div {
 2  color: orange;
 3}
 4.important {
 5  color: red;
 6}
 7
 8#target1 {
 9  color: blue;
10}
11
12#target2.important {
13  color: green;
14}
15/*div#target2.important {
16  color: yellow;
17}*/

Css cascading result

Edit the code and do your experiment in jsFiddle.

What’s next? We’re going to take a look at “Project requirement”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content