DEV Community

Richard Terungwa Kombol
Richard Terungwa Kombol

Posted on

CSS morsel for today: understanding CSS initial values using the unset keyword

From its description in the MDN docs, the unset CSS keyword is described as a way to reset a CSS property to its inherited value if the property naturally inherits from its parent, and to its initial value if not.

To understand what this means, say, in a contrived scenario, we are using a CSS media query to render a CSS class that behaves differently on mobile and desktop screens.

.Socials__wrapper--mobile {
  display: flex;
  align-items: center;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 3.4375rem;
  background-color: #fffdf9;
  z-index: 1;
}
Enter fullscreen mode Exit fullscreen mode

The snippet above is meant to run on mobile screens. It is also the default styling for the class Socials__wrapper--mobile. But we want the Socials__wrapper--mobile to behave differently on desktop screens. We do not want certain property values to carry over to desktop styling. On the desktop, we don't want bottom, right, height, or width to be defined. We do this by setting these properties to unset in the media query as shown below.

@media only screen and (min-width: 1024px) {
  /* This should run on tablets and desktops.  */
  .Socials__wrapper--mobile {
    bottom: unset;
    right: unset;
    width: unset;
    height: unset;
    background-color: #fffdf9;
    z-index: 1;
  }
}
Enter fullscreen mode Exit fullscreen mode

Note that the properties bottom, right, width, and height is referred to as non-inherited properties. This means that they don't automatically inherit their values from the encapsulating parent element like say a color property would. And because of this, assigning unset to them means the browser (also referred to as the user agent) assigns the default values defined in the CSS specifications to the properties.

The initial value for the box-model (width, height) and position (top, bottom, etc) properties as defined in the specification is auto. If we replace the unset keyword with auto we get the same effect.

@media only screen and (min-width: 1024px) {
  /* This should run on tablets and desktops.  */
  .Socials__wrapper--mobile {
    bottom: auto;
    right: auto;
    width: auto;
    height: auto;
    background-color: #fffdf9;
    z-index: 1;
  }
}
Enter fullscreen mode Exit fullscreen mode

It is important that auto is the keyword to signify that the browser (user agent) needs to compute this property automatically taking into consideration the context and content. The context could be the behaviour of the parent element.

Top comments (0)