Facebook Pixel

Inherit

The inherit keyword in CSS allows an element to take (or "inherit") the property value from its parent element. This is useful when you want to maintain a consistent style across nested elements without repeating the same code everywhere.

You can apply inherit to individual properties like color, font-size, etc., or use all: inherit; to inherit all possible properties at once.

Example 1: Inheriting a Single Property

In this example, the child paragraph (<p>) will inherit the text color from its parent (div).

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Inherit Example</title>
  <style>
    div {
      color: darkblue; /* Parent property */
      border: 2px solid black;
      padding: 10px;
    }

    p {
      color: inherit; /* Inherit text color from parent */
      font-size: 18px;
    }
  </style>
</head>
<body>
  <div>
    <h2>Parent Container</h2>
    <p>This text inherits the color from its parent container.</p>
  </div>
</body>
</html>

Output: inheritance example

  • The heading (<h2>) has the default black color (since we didn’t set it to inherit).
  • The paragraph text inherits darkblue from the parent <div>.

Example 2: Using all: inherit

Instead of applying inheritance property by property, you can apply:

all: inherit;

This forces the child element to inherit all applicable properties from its parent.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS All Inherit Example</title>
  <style>
    div {
      color: green;
      font-family: Arial, sans-serif;
      font-size: 20px;
      border: 2px solid gray;
      padding: 10px;
    }

    span {
      all: inherit; /* Inherit everything from parent */
    }
  </style>
</head>
<body>
  <div>
    <p>This is a <span>child span</span> inside a parent div.</p>
  </div>
</body>
</html>

Output: inheritance example

  • The <span> text inherits color, font, size, and other styles from the <div>.
  • It looks exactly like the surrounding text.