What is the difference between the initial and unset values?

According to your link:

unset is a CSS value that's the same as "inherit" if a property is inherited or "initial" if a property is not inherited

Here is an example:

pre {
  color: #f00;
}
.initial {
  color: initial;
}
.unset {
  color: unset;
}
<pre>
  <span>This text is red because it is inherited.</span>
  <span class="initial">[color: initial]: This text is the initial color (black, the browser default).</span>
  <span class="unset">[color: unset]: This text is red because it is unset (which means that it is the same as inherited).</span>
</pre>

A scenario where the difference matter is if you are trying to override some CSS in your stylesheet, but you would prefer the value is inherited rather than set back to the browser default.

For instance:

pre {
  color: #00f;
}
span {
  color: #f00;
}
.unset {
  color: unset;
}
.initial {
  color: initial;
}
<pre>
  <em>Text in this 'pre' element is blue.</em>
  <span>The span elements are red, but we want to override this.</span>
  <span class="unset">[color: unset]: This span's color is unset (blue, because it is inherited from the pre).</span>
  <span class="initial">[color: initial]: This span's color is initial (black, the browser default).</span>
</pre>

I would like to quote the official CSS|MDN documentation for future reference when looking into the differences between each:

INITIAL

The initial CSS keyword applies the initial value of a property to an element. It is allowed on every CSS property and causes the element for which it is specified to use the initial value of the property.

Therefore according to your example:

em {
    color:initial;
    /* color:unset; */
}
<p style="color:red!important"> 
    this text is red 
    <em> 
       this text is in the initial color (e.g. black)
    </em>
    this is red again
</p>

Note how the initial property retains the initial the color property of the element.

UNSET

The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.

Therefore according to your example:

em {
  /* color:initial; */
  color:unset;
}
<p style="color:red!important"> 
  this text is red 
  <em> 
    this text's color has been unset (e.g. red)
  </em>
  this is red again
</p>

Note how the unset property simply resets the color property of the element.

IN CONCLUSION

The idea is quite straight forward, but in practice I would advice caution when dealing with cross browser compatibility for both CSS properties... that is as of today.

Tags:

Css