CSS Tutorial
CSS Advanced
CSS Responsive
CSS Grid
CSS Specificity
If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will “win”, and its style declaration will be applied to that HTML element.
Think of specificity as a score/rank that determines which style declaration are ultimately applied to an element.
Look at the following examples.
HTML
Hello!
CSS
.test {color: green;}
p {color: red;}
Output

Specificity Hierarchy
Every CSS selector has its place in the specificity hierarchy.
There are four categories which define the specificity level of a selector:
Inline styles – Example:
IDs – Example: #navbar
Classes, pseudo-classes, attribute selectors – Example: .test, :hover, [href]
Elements and pseudo-elements – Example: h1, :before
How to Calculate Specificity?
Memorize how to calculate specificity!
Start at 0, add 100 for each ID value, add 10 for each class value (or pseudo-class or attribute selector), add 1 for each element selector or pseudo-element.
Consider these three code fragments
Example
A: h1
B: h1#content
C: <h1 id=”content” style=”color: pink;”>Heading</h1>
The specificity of A is 1 (one element selector)
The specificity of B is 101 (one ID reference + one element selector)
The specificity of C is 1000 (inline styling)
Since the third rule (C) has the highest specificity value (1000), this style declaration will be applied.
More Specificity Rules Examples
Equal specificity: the latest rule wins – If the same rule is written twice into the external style sheet, then the latest rule wins:
This is a div
CSS
div#a {background-color: #03989E;
color:#fff;}
#a {background-color: yellow;}
div[id=a] {background-color: blue;}
Output

the first rule is more specific than the other two, and will therefore be applied.
Contextual selectors are more specific than a single element selector – The embedded style sheet is closer to the element to be styled. So in the following situation
Example
From external CSS file:
#content h1 {background-color: red;}
In HTML file:
<style>
#content h1 {background-color: yellow;}
</style>
the latter rule will be applied.
A class selector beats any number of element selectors – a class selector such as .intro beats h1, p, div, etc.
HTML
This is a heading
CSS
.intro {background-color: yellow;}
h1 {background-color: red;}
Output
