Cascading

We are finally ready to answer two important questions:

  • What happens when there are conflicting instructions on how to style an element?
  • What does cascading, the C in CSS mean?

As you have probably guessed, we can answer both questions at once. Cascading refers to how styles are determined for elements that are covered by more than one declaration.

Priority by who and how

The priority of styles depends on who created the style (author, user, or browser, in that order) and how the styling information is presented (inline or in a style sheet, in that order). This yields the following order of priority, from highest to lowest.

  1. Inline styles
  2. Internal and external style sheets
  3. User styles for web browser
  4. Default applied by web browser

Since we are trying to avoid the first item where possible (to keep style grouped in stylesheets) and since the third and fourth items are out of our control, in the rest of the module we will mainly focus on the second item.

Priority by what and where

The different selectorsA way of specifying to which parts of a document the declarations in a rule apply. we have considered are not all equal; the priority among selectors depends on their specificity, which we will define shortly. For the moment, all you need to know is that different selectors can have the same priority or different priorities. For a given element, here's how to figure out which value for a property is used:

  • Of all the declarations giving a value for that property that apply to the element, choose the declaration(s) with the highest priority.
  • Of all the declarations chosen in the previous step, choose the one that appears last.

A declaration appears later than another if it appears later in the same style sheet or if it appears in a later style sheet. We will give an example very soon.

Priority by inheritance

There is one other issue that needs to be considered, which is the styling of elements to which no declarations apply, or more precisely, to which no declarations apply directly. Some types of styling can be inherited from an ancestorThe parent or parent of the parent or so on. in the tree representation of the document. We will consider this more shortly.

Summary

For each property, a value is assigned according to the following guidelines:

  • If there is no declaration giving a value for that property that applies to the element, it might inherit a value from an ancestorThe parent or parent of the parent or so on..
  • If only one declaration giving a value for that property applies to the element, the value comes from that declaration.
  • If more than one declaration giving a value for that property applies to the element, of the declarations with the highest priority, the value comes from the one that appears last in the document.