In the code below if I use:
.override{
background-color: pink;
}
Then will it show the same color as it is showing now?
.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>
3
Answers
The
inherit
keyword is used to apply the same value of a property from the parent element to its child element. This means that the child element will inherit the property value of the parent element, effectively making it the same as the parent.Take a look at the docs.
The inherit value can be particularly useful when you want elements to automatically adopt certain styles from their parent elements without having to explicitly specify those styles again. However, it’s worth noting that not all properties can be inherited. Some properties, such as borders and margins, do not inherit by default.
It’s important to carefully consider when to use the inherit value, as it can create unintended consequences if not used appropriately. In some cases, you might want to establish specific styles for child elements that differ from their parents. In those situations, you would avoid using the inherit value.
What is happening here is the cascading as in Cascading style sheets (css).
Both the classes green and override have the same weight so the one that comes after the other wins.
In this snippet I’ve reversed the order and you can see that this time green wins.