Web Platform CSS

Cascading

The 'cascading' part of the name Cascading Style Sheets refers to the fact that how elements are styled depends on a cascade, or chain of rules and based on inheritance according to the HTML structure.

If you style the BODY element, every element inside of it will be affected unless the element has rules which override those set in the BODY. This can be very useful: If you want to set the typeface for everything on the page, set it on the BODY. When you want to override it in specific cases, apply the rule to that subset of elements.

The cascading behaviour can also come into play when sizing or positioning things with relative units. This can be hard to figure out at times.

.parent {
  font-size: 50%;
}
.child {
  font-size: 100%;
}
<div class="parent">
  Parent
  <div class="child">
    Child
  </div>
</div>
.parent { font-size: 50%; } .child { font-size: 100%; }
Parent
Child

In the above example, you might expect 'Parent' to be small, while 'Child' to be larger. The parent element's text is reduced by half of whatever it's initial value is. Because of cascading, the child element's initial size will be the same as its parent. So a setting of 100% keeps it the same as the parent.

Because it can be hard to reason about, be careful about going overboard with inter-dependencies of rules.

The browser starts off with its own default rules about how elements should be styled, and each additional bit of CSS you add potentially overrides it. Rules declared later in the page (or imported later for external stylesheets) override in-built and earlier rules.

Specificity

In general, more specific selectors 'win' over more general selectors. In the following example, 'Two' appears in pink because detail.blah is a more specific selector than either detail or .blah.

<style>
detail {
  color: blue;
}
.blah {
  color: red;
}
detail.blah {
  color: pink;
}
</style>
<detail>One</detail>
<detail class="blah">Two</detail>
One Two