I have a nested div
structure in my HTML, and then I apply some background-color
in the outer div, but the inner div does not inherit that property, how can I achieve that?
.some-class {
background-color: #0b7261 !important;
box-sizing: border-box;
color: white;
padding: 10px;
}
.container {
display: flex;
flex-direction: row;
}
<div >
<div >
<h1>some-text</h1>
</div>
<div >
<div id="some-text1">
<h2>some-text</h2>
<p >some-text</p>
</div>
<div id="some-text2">
<h2>some-text</h2>
<p >some-text </p>
</div>
<div id="some-text3">
<h2>some-text</h2>
<p >some-text</p>
</div>
</div>
</div>
I simply added background-color
to my upper div some-class
When I apply this, there is no background color in the container class.
CodePudding user response:
This doesn't happen by default, in fact, in most cases the elements will be overlapping (as they are in your example) and therefore effectively have the same background anyways.
However, if you specifically want this behavior, you can use the css inherit
keyword
.some-class{
background-color: #0b7261;
box-sizing: border-box;
color :white;
padding: 10px;
}
.container{
display: flex;
flex-direction: row;
background-color: inherit;
}
CodePudding user response:
background-color
simply is not a property that is inherited to child elements. However in most cases, child elements will be inside the parent, and the default setting for background-color
is transparent
, so most child elements will have the parent's background-color (coming through from the parent), as it is visible in your snippet.
For the rare situations where a child element is outside the parent (or partly outside), you can use the inherit
setting for background-color.