What is Specificity in CSS ?

Hey guys sometimes most of us wonder when we apply some property to a CSS element but it does nothing . Well the answer is simple it’s all about priorities. In CSS, selectors (p,div,#,.,etc) have their own priority levels and all you need to know is how to play with them . In this article i’ll give a brief introduction of the priority levels .

Let’s take an example, we have a html file and a separate CSS file .

<html>

<head>
 <link rel=”stylesheet” href=”style.css”>
 </head>

<body>
 <p>My first article</p>
 </body>

</html>

#Element level

Now we try to style the content inside p. if we style our p element like this

p{ color : green}

you will see that the color of “My first article ” turns to green. Now extend the css file

p{ color : green}

P{color:red}

Now the color will turn into red because both selectors contains the same element level priority so according to the general css rules the below one will override the upper one.

#Class level

Now we modify the html file

<html>

<head>
 <link rel=”stylesheet” href=”style.css”>
 </head>

<body>
 <p class=”article”>My first article</p>
 </body>

</html>

and extend the css file

p{ color : green }

P{ color : red }

.article{ color : yellow }

Now you will see that color turns into yellow because the priority of class level is higher .

#Id level

Now we modify the html file

<html>

<head>
 <link rel=”stylesheet” href=”style.css”>
 </head>

<body>
 <p class=”article” id=”articleId”>My first article</p>
 </body>

</html>

and extend the css file

p{ color : green }

P{ color : red }

.article{ color : yellow }

#articleId{color:blue}

Now you will see that color turns into blue because the priority of id level is higher than class level.

#Inline styling

Now we modify the html file

<html>

<head>
 <link rel=”stylesheet” href=”style.css”>
 </head>

<body>
 <p class=”article” id=”articleId” style=”color : purple”>My first article</p>
 </body>

</html>

Now you will see that color turns into purple because the priority of inline styling is higher than id level.

#!important

Now we modify the css file

p{ color : green !important}

P{ color : red }

.article{ color : yellow }

#articleId{color:blue}

Now you will see that color turns into green again and the priority element gets the highest priority because the !important has the highest priority.

#Nesting

Now let’s go back to the square one for understanding this concept.

<html>

<head>
 <link rel=”stylesheet” href=”style.css”>
 </head>

<body>
 <p>My first article</p>
 </body>

</html>

Modify css file like this

body p{ color : green }

P{ color : red }

you will see that the color turns into green. This is called nesting. The more nesting will give more priority.

I hope this article will help you guys.

Like what you read? Give Virendra Pratap a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.