Writing less CSS with inheritance

Apr 17, 2021css-conceptscss

In CSS, inheritance propagates property values from parent elements to their children. The inherited value of a property on an element is the computed value of the property on the element’s parent element. For the root element, which has no parent element, the inherited value is the initial value of the property.

The great thing about inheritance is that you can establish the basis for a consistent visual design with very little code. And these styles will even apply to HTML you have yet to write.

Which properties are inherited by default and which aren’t is largely down to common sense, check out this exhaustive list. Common inherited properties are color, font-family, font-size, font-weight, font, border-collapse, direction, letter-spacing, etc.

When inheritance happens

According to how CSS works to compute final value of a CSS property for a given element, inheritance happens at defaulting phase right after cascading.

1. Collecting
2. Cascading
3. Defaulting
4. Resolving
5. Formatting
6. Transforming

The defaulting step comes in to place when there are no declarations try to set value for a CSS property of an element. There are several ways of defaulting:

  • Initial value: this initial value of a CSS property is defined in its definition table, the usage of initial value depends on whether it is inherited or not.
  • Inheritance: inherited property get value from parent element, root inherited property get initial value, non-inherited property gets initial value all the time.
  • Explicit defaulting: instead of setting custom value for a property, you can explicitly use initial keyword for resetting a property, inherit for explicit inheritance and unset for erasing all declarations.

Inheritance keywords

CSS provides four special universal property values for controlling inheritance. Every CSS property accepts these values.

  • inherit: take the computed value of the property from its parent element.
  • initial: applies the initial (or default) value of a property to an element.
  • unset: resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not.
  • revert: reverts the cascaded value of the property from its current value to the value the property would have had if no changes had been made by the current style origin to the current element.

The CSS shorthand property all can be used to apply one of these inheritance values to (almost) all properties at once. Its value can be any one of the inheritance values above. It’s a convenient way to undo changes made to styles so that you can get back to a known starting point before beginning new changes.