Bonus Reading: CSS Selector Overrides – The Cascade

CSS works a little like genetics. We may inherit the genes for both brown and green eyes, but which color will our eyes be? Likewise, more than one CSS rule can apply to a single HTML element. How does the browser decide which rule to use?

The browser uses what’s called the cascade to choose which rule to display on screen, based on a number of criteria:

  • Class selectors override HTML tag selectors.
  • ID selectors override both class and HTML tag selectors.
  • HTML elements can be nested like china dolls. The more nested an HTML element is, the more specific it is.
  • Rules applied to the innermost nested HTML elements override those applied to the outer HTML elements.
  • Order matters. Rules that appear later in the CSS document override those that appear earlier.

You’ll see some examples of these in action by diving deeper…

Examples

1. Class selectors override HTML tag selectors.

Here’s the HTML:

<p class="body-text">Here is some body text.</p>

Here’s the CSS:

p { 
  color: #000000; 
}
.body-text { 
  color: #d35400; 
}

Here’s how it’ll look on screen:

Body text.

Since class selectors override HTML tag selectors, the “.body-text” rule gets used.

2. HTML elements can be nested like Matryoshka dolls. The more nested an HTML element is, the more specific it is.

<div id="main">
   <p class="body-text">
     <span class="highlight">Here is some text inside a span.</span> Here's text not inside a span.
   </p>
</div>

In this example, the span tag is more specific than the p tag, which in turn is more specific than the div tag.

3. Styles applied to the innermost nested HTML elements override those applied to the outer HTML elements.

Here’s the HTML:

<div id="main">
   <p class="body-text">
     <span class="highlight">Here is some text inside a span.</span> Here's text not inside a span.
   </p>
</div>

Here’s the CSS:

.body-text { 
  background-color: #ffffff; 
}
.highlight { 
  background-color: #000000; 
  color: #ffffff; 
}

Here’s how it’ll look on screen:

Here is some text inside a span. Here’s text not inside a span.

4. Order matters. Rules that appear later in the CSS document override those that appear earlier.

<p>
     What will the background color of this paragraph text be?
</p>

Here’s the CSS:

p { 
  background-color: #000000; 
  color: #ffffff; 
}
p { 
  background-color: #16a085; 
}

Here’s how it’ll look on screen:

What will the background color of this paragraph text be?

In this example, the first line of CSS adds a rule that turns the paragraph text white (#ffffff), with a black background (#000000). The second line of CSS adds a rule that changes the background color of the paragraph to turquoise (#16a085). So we end up with a paragraph that has white text on a turquoise background. Yikes! The background is turquoise because the turquoise rule came last, but the white text remains because no rule was added later that overrides the text color.