As a Frontend Developer, you might have came across the situation, where your CSS isn't working as expected or not getting applied where it should be. And then you end up wasting your time writing wrong CSS or refactoring all styles here and there.
Ugh!!
Here CSS Specificity comes into picture. And why you should know it as a frontend developer.
What is CSS Specificity?
What internet says,
CSS Specificity is the set of rules applied to the CSS selectors to determine which style will be applied to an element.
We know CSS stands for Cascading Style Sheet, and cascading means the sequence of order in which CSS rules will be applied.
Before going ahead, let' revise CSS Selectors.
CSS Selectors
-
Universal Selector
( * )
* {
background-color: red;
}
Universal Selector's style will apply throughout the webpage but it has no
specificity. That means any other style with more points will take over it.
- Inline Styles
<div style="color: red;">Hello World!</h1>
Inline style has highest priority. Which will override other style.
-
IDs
( # )
<div id="my-heading">Hello World</h1>
#my-heading {
color: blue;
}
ID have second highest priority.
- Classes, pseudo-classes and attributes
.my-heading {
color: blue;
}
Classes, pseudo-classes and attributes will have less priority as compare to IDs.
- Elements and Pseudo Elements
div {
color: gray;
}
//pseudo element
::selection {
color: yellow;
}
Elements and Pseudo elements has lowest priority.
- !important
.my-heading {
color: pink !important;
}
An !important
has the highest specificity and will take over all the other CSS properties.
When we use !important, no other style like inline style, ID, class will work.
Let's see some example,
Example 1
ul > li {
color: red;
}
Specificity: 0 - 0 - 0 - 2
list > list-items {
color: blue;
}
Specificity: 0 - 0 - 2 - 0
So, the second will override the first as it has the high specificity.
Example 2
a.my-class.another[href]:hover {
//some properties
}
Specificity: 0 - 0 - 4 - 1
Visualizing Specificity
For inline styling, the specificity will be
For IDs styling, the specificity will be
For Classes, pseudo-classes and attributes styling, the specificity will be
For Elements and pseudo elements styling, the specificity will be
Hope now have understood the CSS Specificity.
Top comments (2)
well articulate
Thank you!