Hierarchy

In previous section, we saw the example of selectors. In this section, we will understand the hierarchy of the styling-operations.

Below is the priority level for the CSS,

  1. Priority level:
    • ID (highest priority)
    • Class
    • Element
  2. If two CSS has same priority, then CSS rule at the last will be applicable

Example: Below is the html code with following tags,

  1. ‘p’ tag
  2. ‘p’ tag with class ‘c_head’
  3. ‘p’ tag with class ‘c_head’ and id ‘i_head’
 
	        1 <!-- css.html -->
2
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <title>CSS Selectors</title>
7 <link rel="stylesheet" type="text/css" href="asset/css/my_css.css">
8 </head>
9 <body>
10 <p>Paragraph</p>
11
12 <p class='c_head'> Paragraph with class 'c_head' </p>
13 <p class='c_head' id='i_head'> Paragraph with class 'c_head' and id 'i_head' </p>
14
15 </body>
16 </html>

Below is the CSS code.

 
	        1 /* asset/css/my_css.css */
2
3 /*class selection*/
4 .c_head{
5 font-family: cursive;
6 color: orange; /*override the blue color*/
7 }
8
9
10 /*id selection*/
11 #i_head{
12 color: red;
13 }
14
15 /*element selection*/
16 p {
17 font-variant: small-caps;
18 color: blue;
19 }
20
21
22 /*element selection*/
23 p {
24 color: green;
25 }

Let’s understand the formatting of all three ‘p’ tags individually.

  1. ‘p’ tag at Line 13 of html: Since, ‘id’ has highest priority, therefore CSS rule for #i_head’ (Line 12) will not be overridden by Line 24; hence the color is red. Line 13 has ‘p’ tag, therefore ‘font-variant’ rule will be applied by Line 17. Also, this tag has class ‘c_head’, therefore ‘font’ will be set to ‘cursive’. Hence, the line is “all-caps with font-cursive in red color”.
  2. ‘‘p’ tag at Line 12 of html: Similarly, the ‘head’ tag has higher priority than ‘element’ therefore color of this line is oranage and font-family is ‘cursive’. Also, Line 17 will make it all caps.
  3. ‘p’ tag at Line 10 of html: Color defined at Line 18 will be overridden by Line 24; hence the color will be blue. Also, Line 17 will make it all caps.

© Copyright 2025 | FolkLight Studios