CSS selector priority
There are many ways to apply the design style to the desired element. But what happens if one element chooses two or more mutually exclusive selectors? This dilemma is solved with the help of two principles of CSS: the specificity of selectors and cascade.
The specificity of selectors determines their priority in the style sheet. The more specific the selector, the higher its priority. To calculate the specificity of the selector, three groups of numbers (a, b, c) are used, the calculation is made as follows:
- It is counted the number of identifiers in the selector (group a)
- It is counted the number of class, attribute and pseudo-class selectors in the selector (group b)
- It is counted the number of type selectors and pseudo-elements in the selector (group c)
- The selector inside the pseudo-class
:not
is considered as any other selector, but the pseudo-class:not
does not participate in calculating the specificity of the selector - The universal selector (
*
) and combinators do not participate in calculating the selector specificity
In the example, the selectors are arranged in order of increasing their specificity:
* /* a=0 b=0 c=0 -> specificity = 0 */ li /* a=0 b=0 c=1 -> specificity = 1 */ ul li /* a=0 b=0 c=2 -> specificity = 2 */ ul ol+li /* a=0 b=0 c=3 -> specificity = 3 */ h1 + *[rel=up] /* a=0 b=1 c=1 -> specificity = 11 */ ul ol li.red /* a=0 b=1 c=3 -> specificity = 13 */ li.red.level /* a=0 b=2 c=1 -> specificity = 21 */ #x34y /* a=1 b=0 c=0 -> specificity = 100 */ #s12:not(p) /* a=1 b=0 c=1 -> specificity = 101 */
The highest priority has a number from group a
, the number of group b
has an average priority, the number from group c
has the lowest priority. Numbers from different groups can not be summed up into one common; we take from the example the last line with the selector specificity 101
- this does not mean the number one hundred one
, it means that one selector from group a
(identifier) and one selector from group c
(type selector) was used.
The inline style has a higher priority than the style defined in the internal or external style sheet. However, if you specify a special !important
declaration for a particular property in the internal or external style sheet, then it will have a higher priority than the value of a similar property in the inline style. The !important
declaration is specified after the property value before the semicolon:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Page title</title> <style> #one { color: red; } #two { color: blue !important; } </style> </head> <body> <p id="one" style="color: yellow;">The first paragraph.</p> <p id="two" style="color: yellow;">The second paragraph.</p> </body> </html>Try it »
With this theme look: