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:

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 »
Copying materials from this site is possible only with the permission of the site administration and
when you specify a direct active link to the source.
2011 - 2021 © puzzleweb.ru

puzinfo@puzzleweb.ru | ruen