CSS tutorial series: Inheritance

fullstackjo

The daily developer

Posted on January 15, 2023

CSS tutorial series: Inheritance

When a property on an element is left empty in CSS, inheritance determines what happens.
CSS properties fall into one of two categories:

  • Inherited properties

  • Non-Inherited properties

Inherited properties

An element receives the value of an inherited property from its parent element when the value for the property has not been specified on the element. (font-size, font-family, font-weight, color etc...)

Let's see an example

<div class="parent">
  <div class="child"> child 1</div>
  <div class="child"> child 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.parent {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

The parent div in this case has red as its styling color. The child classes, however, were displayed in red despite not having the "color: red" rule set for them.
Because the parent's properties were passed down to the child divs 1 and 2.

Non-Inherited property

An element gains the initial value of a non-inherited property when no value for that property has been specified on the element. (weight, height, padding, border etc...)

<div class="container">I am a <span>Container</span></div>
Enter fullscreen mode Exit fullscreen mode
.container {
  border: 3px solid green;
}
Enter fullscreen mode Exit fullscreen mode

The border property won't be inherited by the span element, meaning it will not have a border since the initial value of border-style is none.

However if we would like the span to inherit that border and be displayed around the container word we will need to use the keyword inherit which will specify inheritance in an explicit manner.

.container {
  border: 3px solid green;
}

span {
  border: inherit
}
Enter fullscreen mode Exit fullscreen mode

Image description

It applies to properties that are inherited and those that are not.

đź’– đź’Ş đź™… đźš©
fullstackjo
The daily developer

Posted on January 15, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related