I was reading MDN docs about inherit keyword and the example there is very confusing to me can anyone PLEASE explain to me the exact example on MDN docs about excluding selected elements from the rule. Thank you.
Examples
Exclude selected elements from a rule
/* Make second-level headers green */
h2 { color: green; }
/* ...but leave those in the sidebar alone so they use their parent's color */
#sidebar h2 { color: inherit; }
In this example, the h2 elements inside the sidebar might be different colors. For example, if one of them were the child of a div matched by the rule ...
div#current { color: blue; }
... it would be blue.
It is my first time asking question so please don't mind my formatting.
CodePudding user response:
Let's take it step by step in this snippet:
/* Make second-level headers green */
h2 {
color: green;
}
/* ...but leave those in the sidebar alone so they use their parent's color */
#sidebar h2 {
color: inherit;
}
div#current {
color: blue;
}
<h2>this is an h2 outside the sidebar so it should have the color set for h2 in the style sheet which is green.</h2>
<div id="sidebar">
<h2>This is an h2 inside the sidebar so it has inherited its parent's color - which in this example is the default which is black</h2>
<div id="current">
<h2>This is an h2 inside a div. The div has id current and color blue. This h2 has inherited its parent's color which is blue.</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Are you looking for this example?
h2 {
color: green;
}
.sidebar h2 {
color: inherit;
}
.sidebar {
color: blue;
}
.red {
color: red;
}
<h2>This is Green Heading</h2>
<div class="sidebar">
<h2>This is Blue Heading</h2>
<div class="red">
<h2>This is Red Heading</h2>
</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
the first h2 element will be green, because it has a css rule. The second h2 for example became black because he has the rule inherit so he get the color of his parent.
If sidebar has another parent with color declared, h2 get this color
h2 {
color: green
}
div#current {
color: blue;
}
.sidebar h2 {
color: inherit
}
<h2> Green </h2>
<div class="sidebar">
<h2>Default color</h2>
</div>
<div id="current">
<div class="sidebar">
<h2>Default color</h2>
</div>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>