Cyrus Yip's blog

Introduction to Cascade in CSS

Cyrus Yip
Table of Contents

The cascade is the algorithm that determines the correct rule when multiple CSS rules apply to an HTML element.

The cascade is determined by several factors (from least important to most important):

  1. source order (least important)
  2. specificity
    1. type
    2. class
    3. id
  3. inline styles
  4. !important (most important)

Source order #

Later declared rules override previous rules.

1
<p>Hello, world!</p>
1
2
3
4
5
6
7
p {
  color: green;
}
p {
  /* This rule wins */
  color: blue;
}

Specificity #

Specificity determines the importance of a selector. In general, the more specific a selector is, the more weight is has.

For example, an id selector is more specific than a type selector, so the id selector has more weight.

1
<p id="p">Hello, world!</p>
1
2
3
4
5
6
7
#p {
  /* This rule wins */
  color: green;
}
p {
  color: blue;
}

Specificity calculation #

The specificity score is calculated using three components:

Specificity scores are compared by comparing three components in order. The specificity score with a larger A value is higher. If two A values are equal, compare B values. If two B values are also equal, compare C values. If all values are equal, two specificity scores are equal. For example, (1,0,0) is larger than (0,2,0).

When you inspect an element using devtools and hover the cursor to a selector of a style declaration, you will see the specificity score in the form of Specificity: (A,B,C).

Here are some specificity score examples:

SelectorA (ID)B (Class)C (Type)Score
*0000,0,0
p0010,0,1
div.highlight0110,1,1
main .table-wrapper > table0120,1,2
#avatar1001,0,0

Inline styles #

Inline styles are declared inside a style attribute. Inline styles have the highest specificity score (1,0,0,0).

1
<p style="color: blue;" id="p">I am blue</p>
1
2
3
#p {
  color: green;
}

!important #

!important flag overrides all other factors (source order, specificity, and inline styles).

1
<p style="color: blue;" id="p">I am green</p>
1
2
3
#p {
  color: green !important;
}

!important can make CSS work unexpectedly. Don’t use it unless you really need it.


References #

Further reading #

Test #

Tags: