Don't forget initial, inherit and unset

, by

A little reminder of two CSS keywords too often underused: inherit (CSS2.1) and initial (CSS3), and a presentation of unset (CSS3), a combination of the two previous ones.

Inherit

  • can be attached to any CSS property
  • takes the property’s value specified in its first encountered parent
body {
    font-weight: 300;
    color: #000;
}

h1 { font-weight: inherit; } /* Output: 300 */

a { color: inherit; } /* Output: #000 */

Using inherit, you can force inheritance for properties that are not inherited by nature (margin, padding, …).

.content { margin: 100px; }

.content .foo { margin: inherit; } /* Output: 100px */

Initial

  • can be attached to any CSS property
  • is used to reset a property to its initial value - or the one set by the user agent ( font-family, color, …) -
body {
    font-weight: 300;
    color: #f00;
}

h1 { font-weight: initial; } /* 'normal' (400) */

/* browser default text color (usually #000) */
a { color: initial; } 

Initial override elements default CSS

/* h1 has a default 0.67em margin top and bottom. */
h1 { margin: initial; } /* Output: 0 */

Unset: combination of initial and inherit

At the time of writing, ‘unset’ only works with Chrome (41) and Firefox (27).

If the property is, by nature, inherited, unset runs inherit. If not it runs initial.

.content { 
    color: #666; /* [1] */
    margin-left: 100px; /* [2] */ 
}

.content .foo {
    color: unset; /* [3] Output: #666 */
    margin-left: unset; /* [4] Output: 0 */
}
  • color is a property that naturally is inherited
  • margin is not inherited
  • because of [1], unset runs inherit
  • because of [2], unset runs initial. Therefore margin-left equals ‘0’

Check it out on jsfiddle.

All

At the time of writing, ‘all’ doesn’t work with safari.

The CSS all property sets every properties of an element to its initial, inherited or unset value. Possible values are inherit | initial | unset

.content { 
    color: #666;
    margin-left: 100px; 
}

.content .foo {
    all: unset; /* color: #666; margin-left: 0; */
}

TL;DR : Why you should use it more

Less constant declarations

Using keywords, known as CSS-wide keywords, is interesting because – the way any variable would do - they “carry” values, which means we can declare values a minimum of time.

/* #666 is declared twice */
.content { color: #666; }

.content a { color: #666; }

/* Using inherit, one time is enough */
.content { color: #666; }

.content a { color: inherit; } /* Output: #666 */

Better understanding of the code

CSS keywords help us and the team to interpret the code. In the previous example, the first block can be interpreted as : “We want all the links to be gray” while the second one means : “We want all the links to be the same colour as the content (regardless the colour)” - which is a much better way to analyse your UI -.