DEV Community

Madeline
Madeline

Posted on • Updated on

Inheritance in CSS

In this post I will explain what inheritance is in CSS, why it's useful, and how to take advantage of it.

If you're like me, you may have dabbled with CSS, heard thar some values of properties are inherited, and been generally confused by the whole thing.

First let's make sure we understand what a CSS property and value is. Together, they tell us what style we are applying to a selector.. The property is the thing within the declaration block that tells what you are declaring a value on: things like padding, color, font-family, and so forth. The value tells us the actual style: things like 30px, blue, and Arial.

So what exactly is inheritance? Inheritance takes place when values for some specific properties are passed down from parent elements to their children. A parent element is the selector that refers back to the html tag that contains the child element.

For example:

Alt Text

So, we can select .parent and .child in our css file, and some select properties that we declare on .parent will apply to .child as well.

Why is inheritance important? It allows us to achieve more easily responsive websites without writing a lot of extra code with complicated calculations. It makes code more maintainable. If you declare a value for a property, your declared value overrides inheritance, but inheritance can be a nice way to write less code, rather than declaring "font-size: 16px" in every single element!

How does inheritance work? The computed value of a property gets inherited - not its declared value. For example, let's say you write your font-size as 1.5rem (with a root font-size of 16px). That value gets parsed and is computed to 24px. In the child section, the font-size 24px gets inherited, because it is the computed value that was declared by the 1.5rem in the parent element.

What kinds of properties are inherited? Properties related to text, like font-family, font-size, color. Properties which are not inherited are things like padding, margins. Although, you can force inheritance by using the inherit keyword. You can reset a property to its initial value by using the initial keyword.

Top comments (0)