CSS Specificity and it’s importance(2/2)
How to calculate CSS specificity?
Before we move further let’s revise what we have learned in first article. We have seen importance of CSS specificity and why it is important for developers to know about it.
CSS Specificity
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element. [ Reference : Mozilla Website ]
Let’s continue further. First thing we should know before learning ‘how to calculate specificity’ is CSS Selectors & Specificity Hierarchy.
CSS Selectors
A CSS selector is the part of a CSS rule set that actually selects the content you want to style. [ Reference : CSS Selectors ]
If you are working with CSS you should be aware of these CSS selectors.
- Universal Selector [
*
] - ID Selector [
#idOfElement
] - Class Selector [
.classNameOnElement
] - Element Selector [
div
] - Attribute Selector [
input[type="text"] ]
- Descendant Selector [
div .test
] - Child Selector [
div > .test
] - Adjacent Sibling Selector [
div + div
]
Above mention list contains some of the general selectors that we usually used in our development. I recommend to go through this article first.
Specificity Hierarchy
Specificity hierarchy determines which selector ( i.e. id , class , element) has highest priorities. There are four level which define the specificity level of different selectors. Below is the list containing priority ordering from highest to lowest.
- Inline styles.
<p style=“color: #000;”>Hello World</p>
- IDs : identifier for element.
HTML: <p id="test"><p> | CSS : #test { color:#fff }
- attributes,Classes and pseudo-classes
.classs , [attributes] and div:hover , div:active
- Elements and Pseudo-elements
div, p , p:after , p:before
Specificity Calculations
Now that we have learn what is selector and and what is hierarchy. It’s time to learn CSS SPECIFICITY CALCULATION.
First remember this diagram.
Description:
- If the element has inline styling, that automatically 1 wins (1,0,0,0 points)
- For each ID value, apply 0,1,0,0 points
- For each class value (or pseudo-class or attribute selector), apply 0,0,1,0 points
- For each element reference, apply 0,0,0,1 point
Let’s see few examples
Important Notes
- The universal selector (*) has no specificity value (0,0,0,0)
- Pseudo-elements (e.g. :first-line) get 0,0,0,1 unlike their psuedo-class brethren which get 0,0,1,0
- The pseudo-class :not() adds no specificity by itself, only what’s inside it’s parentheses.
- The !important value appended a CSS property value is an automatic win. It overrides even inline styles from the markup. The only way an !important value can be overridden is with another !important rule declared later in the CSS and with equal or great specificity value otherwise. You could think of it as adding 1,0,0,0,0 to the specificity value.
Wrap Up
In this article we have seen how to calculate specificity and it’s basic rules and important notes on specificity calculation.