In this article, I will talk about specificity in CSS and how it works.
It is basically a good way to add styles to an HTML element. Sometimes we face some unexpected behaviour while adding any style like class or style are not getting added to the element. Here the problem is that you have not checked the hierarchy of CSS styles in what order they are added.
It is important to know when to add styles on class, id, HTML tag or selector while assigning a style. If you are not choosing these things wisely this may create problems. specificity gives you an order of styling the template.
So, assign class or style to the element according to the CSS specificity.
Here is the preference level that you can check-
SCORE — SELECTOR
0.0.0.0.0 — *
0.0.0.0.1 — element or pseudo-element
0.0.0.1.0 — class, pseudo-class, or data attribute
0.0.1.0.0 — ID
0.1.0.0.0 — Inline style
1.0.0.0.0 — !important
Here specificity will increase according to the level which means example id can override the styles of class.
Example-
<p id=”thing”>Will be RED.</p>p {color: red}#thing {color: green;}
Here we assigned style using two things p HTML element and the thing id attribute. According to our specificity order, we can easily find out which colour the text will show. ID selector has higher specificity. So, it will show the green colour of the text.
If you want to make the text colour red then you have to use an important keyword.
p {color: red !important;}
It makes the text colour red. But it is not a good practice. Keep this! Important keyword is the last option. If nothing works then use this.
Another example-
<blockquote><p>What color is the blockquote?</p></blockquote>blockquote {font-style: italic;background: yellow;}blockquote {background: pink;}
Here paragraph element shows pink background colour and italic type text. If you want to change the colour of the p element you can do this by adding the p tag in CSS or by adding class to the p element.
p {color: light green;}
The next case is if you want to add the colour on all text elements-
<blockquote><span>What happened to this text?</span><p>What happened to this text?</p><p class=”text”>What happened to this text?</p><p class=”text” id=”words”>What happened to this text?</p><p class=”text” id=”words” style=”color:pink”>What happened to this text?</p></blockquote>#words {color: lightblue;}.text {color: yellow;}p {color: lightgreen;}blockquote {color: white;background: black;}
Other important resources-
https://www.instagram.com/p/CJMBaYXgXdw/
https://css-tricks.com/specifics-on-css-specificity/
Please clap it, share it and follow me for more updates. Leave a comment below, and let me know what you think!