Loading lesson path
Each type of CSS selector has a position in the specificity hierarchy, and the selector types carry different "weights".
<h1 style="color: pink;">Highest priority, will override all other selectors
#navbar
Formula
1 - 0 - 0
Classes, attribute selectors and pseudo - classes.test, [type ="text"], :hoverFormula
0 - 1 - 0
Elements and pseudo - elements h1, ::before, ::afterFormula
0 - 0 - 1*, where()
Formula
0 - 0 - 0Formula
The weight notation uses three numbers (X - Y - Z):X - Number of ID selectors Y
Formula
- Number of class selectors, attribute selectors, and pseudo - classesZ
Formula
- Number of element selectors and pseudo - elementsThe selector with the higher leftmost number wins. If equal, compare the next number, and so on.
Formula
The declaration with the highest specificity/weight value will be applied to the element.<html> <head> <style>
#demo {color: blue;} /* weight: 1-0-0 */
p#demo {color:
orange;} /* weight: 1-0-1 WINS! */.test {color: green;}Formula
/* weight: 0 - 1 - 0 */p.test {color: green;} /* weight:Formula
0 - 1 - 1 */p {color: red;} /* weight: 0-0-1 */</style> </head> <body> <p id="demo" class="test">Hello World!</p> </body> </html>
Understand how specificity works in different scenarios:
If the same rule is written twice in the external style sheet, the latest rule wins:
Example h1 {background-color: yellow;}
h1 {background-color: red;}Look at the following code lines - Here, the first rule has higher specificity than the second, and will therefore be applied:
#myDiv {background-color: yellow;}
div[id=myDiv] {background-color: blue;}A class selector such as .intro beats h1, p, div, etc:
Example.intro {background-color: yellow;}
h1 {background-color:
red;}
The universal selector (*)
The universal selector (*) has no specificity weight value:* {background-color: yellow;}
h1 {background-color: red;}The embedded style sheet is closer to the element to be styled. So in the following situation the last rule will be applied:
/*From external CSS file:*/
#content h1 {background-color: red;}/*In HTML file:*/ <style>
#content h1 {background-color:
yellow;}</style>