Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "cascading' in CSS?

"Cascading" in this context means that because more than one stylesheet declaration could apply to a particular piece of HTML, there has to be a known way of determining which specific stylesheet rule applies to which piece of HTML.

The rule used is chosen by cascading down from the more general declarations to the specific rule required. The most specific declaration is chosen.


When I teach CSS, I always tell the students that "cascading style sheets" means something like "fighting style sheets".

One rule tells your H3 tag to be red, another rule tells it to be green -- the rules are contradicting each other, who will win!? Stylesheet deathmatch!

OK maybe that's a slight exaggeration, but it's far more amenable to non-code, non-programming people who are just starting out than any notion of a cascade, or inheritance.

I do of course make sure to tell them that it's not a problem for the style sheets to be fighting each other, that's the way the language was designed.


Håkon Wium Lie (CSS co-creator) defines "cascade" in his PHD-thesis on CSS as "The process of combining several style sheets and resolving conflicts between them" https://www.wiumlie.no/2006/phd/


The following article answers your question perfectly.

It's the order in which properties are applied on a particular element(s).

http://www.blooberry.com/indexdot/css/topics/cascade.htm


You have to think of it from the outside in. If you have a rule that that is on the body tag it will "cascade" through every child tag. If you put a rule on any tag inside the body it will adopt that rule, and so on. So the rule cascades through all the content unless interrupted by a rule from an embedded tag.


You can treat the CSS processing as a waterfall contains several cascades. Here are those cascades from top to bottom in order: (The lower can override the same property in the higher.)

  1. user agent declarations
  2. user normal declarations
  3. author normal declarations
  4. author important declarations
  5. user important declarations

See more in the spec

The cascading is to pick the right value from multiple origins. But it's different from sorting. Only something not in order need we to sort. But in CSS these origins have fixed precedence. And thus the pseudo-code might look like the follows:

  1. initialize the value array;
  2. apply the values from 1st origin;
  3. apply the values from 2st origin, override if the value exists;
  4. ...
  5. apply the values from Nth origin, override if the values exists;

From the pseudo-code you can see it quite looks like a waterfall of several cascades.