“Cascading” in CSS
The “cascading” in “Cascading Style Sheets” has several facets: computed values, inheritance, and specificity. Understanding how these cascades work is an integral part of your css ninja training.
Computed Values
Many of the values assigned have a unit. Some of these are relative (like em and <span>), and some are absolute (like px and in). Relative values are based on their parents: an element with a width of 50 uses the element’s parent to determine the actual width of the element.
Likewise, if both the parent and child elements’ font-sizes are 1.5em, the child’s actual font size will be larger than the parent’s.
Absolute values do not change based on their parent values. These are often obvious: color: red; for example. Pixel values are absolute, though the actual value displayed by the UA(User Agent) may differ (due to display or text-size settings).
Inheritance
Inheritance is the passing on of attributes from parents to children. It works in CSS like this: An element’s font color is set to red. The color for its child elements will also be red (if left unspecified or set to inherit).
Specificity
This is how CSS decides between competing styles. Take a look at the following code:
p#special_error { color: red; }
.error { color: orange; }
p { color: black; }
<p>no class or id</p>
<p id="special_error" class="error">class and id</p>
<p class="error">p class</p>
<div class="error">div class</div>
<div id="special_error">div id</div>
So what color do the elements end up with? To answer that question, we need to know how the competing selectors are chosen.
Each selector has a particular weight outlined in this table:
| selector | weight | example |
|---|---|---|
| id | 100 | #special_error |
| class | 10 | .error |
| element | 1 | p |
These weights are all added up and the “heaviest” selector set wins. So using the css above, here are the results:
<p>no class or id</p><!-- #000000 -->
<p id="special_error" class="error">class and id</p><!-- red -->
<p class="error">p class</p><!-- orange -->
<div class="error">div class</div><!-- orange -->
<div id="special_error">div id</div><!-- inherits -->



No Comments, Comment or Ping
Reply to ““Cascading” in CSS”