CSS Specificity

CSS Specificity


CSS Specificity
If conflicting declarations can’t be resolved based on their origin, the browser next tries to resolve them by looking at their specificity. 
Each individual CSS Selector has its own specificity value. Every selector in a sequence increases the sequence's overall specificity. 
Selectors fall into one of three different specificity groups: A, B and c. 
When multiple selector sequences select a given element, the browser uses the styles applied by the sequence with the highest overall specificity. 
 
Group A is the most specific, followed by Group B, then finally Group c.
The universal selector (*) and combinators (like > and ~) have no specificity.
Example 1 -
Selecting element simply by

tag

Output - 
As we can see color is changed 
Example 2 - How specificity is used by the browser
#foo {
color: blue;
}
.bar {
color: red;
background: black;
}

 
Here we have an ID selector which declares color as blue, and a class selector which declares color as red and background as black. 
An element with an ID of #foo and a class of .bar will be selected by both declarations. ID selectors have a Group A specificity and class selectors have a Group B specificity. An ID selector outweighs any number of class selectors. 
Because of this, color:blue; from the #foo selector and the background:black; from the .bar selector will be applied to the element. 
The higher specificity of the ID selector will cause the browser to ignore the .bar selector's color declaration.
Now imagine a different CSS implementation: 
.bar {
color: red;
background: black;
}
.baz {
background: white;
}

 
Here we have two class selectors; one of which declares color as red and background as black, and the other declares background as white.
An element with both the .bar and .baz classes will be affected by both of these declarations, however the problem we have now is that both .bar and .baz have an identical Group B specificity. 
The cascading nature of CSS resolves this for us: as .baz is defined after .bar, our element ends up with the red color from .bar but the white background from .baz.