CSS Specificity & It’s Importance (1/2)
What is CSS Specificity and why it is important to know?
Have you ever experienced spinning your head around, while applying CSS over an element. You applied a CSS on an element but hey it’s not working! Why ?
Well, This is the case most of the developers face when they are trying to apply CSS over an element on which other CSS properties are already applied. This already applied properties may be coming from any CSS framework OR existing developed library that you are using OR importing in your application.
Note: There is a feature called
!important
to override everything and give your applied properties a maximum preference.
But most of the time if you see developers used to avoid use of !important.
Ahh! Then what do other options we have? Solution is : CSS Specificity
Note: There are certain cases where you required to use
!important
. Below are the links where you can find out when to apply!important
property.
Still not understood? Let me give you an example of specificity by the help of problem.
Let’s say i want to apply some styling on first li
element from ul.
I will go ahead and create class named firstLink
and applied CSS property there. That will something look like this.
but, when you run the code in the browser and check, you see there is no color (i.e. #3f51b5
) applied on li
element. oh! how ? why ? Then you will go ahead and debug your code and find out something like below is already applied to the same element.
You will see text-color in your li
element is black
instead of #3f51b5
.Think for a second how this happened ?
There comes Specificity concepts. Issues is selector ul#order-list li
is more specific as compared to .firstLink
. This is just a small example of specificity. Imagine if you are importing any CSS framework’s library or library which is been developed by someone else then chances are huge that they have used high amount of specificity to avoid conflicts. Hence you should know how to use specificity to override their’s in order to apply your own CSS in your application. Here are some of the examples of specificity.
div.testClass > p#testID div > input[type="text"] > i.iconClasss
ul > li ul li ol li:first-letter
div p > div p > div > p div > div.icon p
Hence, it is important to know about specificity and how browser calculates Specificity.
Wrap up
We have learned What is specificity and why it is important ?
What is Specificity?
If two or more CSS selectors are applied on same elements , the one with higher specificity wins.
Why it is important ?
In order to use your css on some element in case some properties are already applied on that element.
In next article we will going to learn about Specificity calculation, Specificity hierarchy , specificity rules ,principles, common solution etc. See you in next article!