What does the inherit keyword in CSS do?

Viewed 9856

Can somebody please explain what the inherit keyword means in CSS and how it works?

2 Answers

It will use the same value as the same property its parent has.

body {
   margin: 234px;
}
h1 {
   margin: inherit; /* this equals 234px in this instance */
}
<body>
   <h1></h1>
</body>

If there are multiple instances of <h1> in the file, it will take the margin of its parent, so 234px is not always the value it will have. For example:

<body>
    <h2></h2>
    <div>
        <h2></h2>
    </div>
</body>
body {
    margin: 20px;
}
div {
    margin: 30px;
}
h2 {
    margin: inherit; /* 20px if parent is <body>; 30px if parent is <div> */
}

To clarify, inherit doesn't do anything unless you're using it to override another style rule, otherwise it's just reinforcing the default behavior. Note that the overriding rule should be higher specificity or be below the rule that it overrides.

.pink {
background-color:pink;

}
.green {
background-color:lightgreen;
}

.override {
background-color:inherit;
}
<div class="pink">
  <p class="green">I'm classed "green", and I am green.</p>
  <p class="green override">I'm also classed "green" but `inherit` overrides this and causes me to inherit pink from my parent.</p>
</div>

Related