Will Oller .com

Avatar

Learning to match the beat of the Old World man.

Tweet:

Back to work today!

“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 @%), 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.

width: 50%
width: 50%

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.

1.5em 1.5em 1.5em

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 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).

color: red
no color specified
color: inherit

Specificity

This is how CSS decides between competing styles. Take a look at the following code:

CSS:
  1. p#special_error { color: red; }
  2. .error {         color: orange; }
  3. p {              color: black; }

HTML:
  1. <p>no class or id</p>
  2. <p id=“special_error” class=“error”>class and id</p>
  3. <p class=“error”>p class</p>
  4. <div class=“error”>div class</div>
  5. <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:

selectorweightexample
id100#special_error
class10.error
element1p

These weights are all added up and the “heaviest” selector set wins. So using the css above, here are the results:

HTML:
  1. <p>no class or id</p><!– #000000 –>
  2. <p id=“special_error” class=“error”>class and id</p><!– red –>
  3. <p class=“error”>p class</p><!– orange –>
  4. <div class=“error”>div class</div><!– orange –>
  5. <div id=“special_error”>div id</div><!– inherits –>

Links

w3.org
wikipedia
htmlhelp

Fuck you, Detriot.

youwouldntbuyour1

Tweet:

I’m sick. It’s so lame to call in sick right before a vacation.

Tweet:

Christmas party!

Continue Next page