CSS Cascade & Inheritance

Learn how CSS determines which styles apply to elements and how properties pass from parents to children

What is the CSS Cascade?

The CSS cascade is the system that determines which style rules apply to an element when multiple rules could apply. It follows this priority order:

1. Importance

Whether !important is used and the rule's origin

2. Specificity

How specific the selector is

3. Source Order

Which rule appears last in the CSS

Understanding Specificity

Specificity Calculation

Specificity is calculated using a 4-value system (a, b, c, d):

  • a: Inline styles (1 if present, 0 otherwise)
  • b: Number of ID selectors
  • c: Number of class, attribute, and pseudo-class selectors
  • d: Number of element and pseudo-element selectors

Specificity Examples

#nav .active a:hover /* 0,1,2,1 */
div#header ul li a /* 0,1,0,4 */
.button.primary /* 0,0,2,0 */
body div p /* 0,0,0,3 */
p /* 0,0,0,1 */

Note: When comparing specificities, start from left (a) and move right. A selector with higher a value wins regardless of b, c, or d values.

Cascade Example

Try This Code

/* Specificity example */
div#main .content p {  /* Specificity: 1-1-2 */
  color: blue;
}

.container p {         /* Specificity: 0-1-1 */
  color: red;
}

p {                    /* Specificity: 0-0-1 */
  color: green;
}

Importance and Source Order

!important Rule

The !important flag changes the priority of a declaration, making it override any other declaration regardless of specificity.

.button {
background-color: blue !important;
color: white;
}

Warning: Overusing !important makes CSS harder to maintain. Use it sparingly!

Source Order

When two rules have equal importance and specificity, the one that appears later in the CSS wins.

.text {
color: red;
}

.text {
color: blue; /* Wins because it's later */
}
< Previous ( Comments )Next ( Secificity ) >