/

Understanding CSS Inheritance and Its Importance

Understanding CSS Inheritance and Its Importance

CSS Inheritance is a concept where properties set on a selector are inherited by its children. While not all properties exhibit this behavior, it helps in writing concise and efficient CSS code by avoiding the need to set the same property for each individual child element.

Certain properties, such as font-related properties, are logical to be inherited, as they can be applied to the parent element and automatically flow down to its children. On the other hand, properties like background color are not intended to be inherited.

Inherited Properties:

Here are some commonly used properties that inherit by default:

  • border-collapse
  • border-spacing
  • caption-side
  • color
  • cursor
  • direction
  • empty-cells
  • font-family
  • font-size
  • font-style
  • font-variant
  • font-weight
  • font-size-adjust
  • font-stretch
  • font
  • letter-spacing
  • line-height
  • list-style-image
  • list-style-position
  • list-style-type
  • list-style
  • orphans
  • quotes
  • tab-size
  • text-align
  • text-align-last
  • text-decoration-color
  • text-indent
  • text-justify
  • text-shadow
  • text-transform
  • visibility
  • white-space
  • widows
  • word-break
  • word-spacing

These properties provide a glimpse of the most commonly encountered inherited attributes. For an extensive list, refer to the Sitepoint article on CSS inheritance.

Forcing Inheritance:

What if you want a property that doesn’t inherit by default to be inherited by the children?

You can achieve this by explicitly setting the property value to inherit in the child selector.

For example:

1
2
3
4
5
6
7
body {
background-color: yellow;
}

p {
background-color: inherit;
}

This forces the background color of the p element to inherit from its parent (body).

Preventing Inheritance:

Conversely, if you want to prevent a property from inheriting, you can use the revert keyword. It resets the property value to the default one established by the browser’s default stylesheet.

In practice, revert is not commonly used; instead, developers tend to overwrite the inherited value by specifying a new value for the property.

Additional Special Values:

Apart from inherit and revert, you can also utilize the following special keywords for properties:

  • initial: Uses the default value defined in the browser’s stylesheet, or, if the property inherits by default, it applies the inherited value. Otherwise, it has no effect.
  • unset: Inherits the property if it is set to inherit by default; otherwise, it has no effect.

tags: [“CSS”, “Inheritance”, “Cascading Style Sheets”, “Web Development”]