Sobes.tech
Junior

How does style inheritance work in CSS?

sobes.tech AI

Answer from AI

Inheritance of styles in CSS occurs on a "from parent to child" basis. Some CSS properties inherit, meaning their value is applied to child elements unless explicitly specified otherwise. Other properties do not inherit.

Examples of inheritable properties:

  • color
  • font-family
  • font-size
  • text-align
  • line-height

Examples of non-inheritable properties:

  • border
  • margin
  • padding
  • background-color
  • width
  • height

Keywords used to control inheritance:

  • inherit: Applies the computed value of the property from the parent element.
  • initial: Resets the property to its default (browser) value.
  • unset: For inheritable properties, works like inherit; for non-inheritable properties, works like initial.
  • revert: Resets the property to the value defined by the user agent stylesheet (browser) or a lower-priority author stylesheet. Essentially, it cancels the effect of later styles.

Example of using inherit:

/* Parent element */
.parent {
  color: blue;
}

/* Child element inherits blue color */
.child {
  /* Explicitly inherit the parent's color */
  color: inherit;
}

Example of using initial:

.box {
  background-color: red; /* Set red background */
}

.inner-box {
  background-color: initial; /* Reset background to default (usually transparent) */
}

Example of using unset:

/* .parent has color: red */
.parent {
  color: red;
}

.child {
  /* color is an inheritable property */
  /* unset works like inherit for color, so child gets color: red */
  color: unset;
}

.box {
  border: 1px solid black;
}

.inner-box {
  /* border is a non-inheritable property */
  /* unset works like initial for border, resetting it to browser default */
  border: unset;
}

Understanding inheritance is important when working with cascade and style specificity. Inherited styles have lower priority than explicitly set styles or styles with higher specificity.