Reputation:
Lets say I have 3 Div's, one called A and the others are B and C, in the CSS, Div A, B and C will always have the same background-color as it is shown in the CSS example below...
div .A {
background-color: black;
}
div .B {
background-color: black;
}
div .C {
background-color: black;
}
My question: Is there anyway I can change the background colour on div A, and then the other divs B and C will actually pull whatever colour applied to A and inherit it? Can I do that using CSS only?
Upvotes: 0
Views: 43
Reputation: 51196
Strictly speaking, no.
There's nothing like class-level inheritance on CSS classes. Properties can propagate through the DOM hierarchy, but there's no straightforward way to make class B and C inherit the background-color from the definition of A. For properties that you want to share in common, you'd typically just apply a common class to those DOM elements.
To put it another way, you can't construct the desired relationship between A, B and C solely in the CSS. With the right DOM, you could do it. But if you don't want B and C to be a child of A in the DOM, then you're out of luck.
Upvotes: 3
Reputation: 2014
You would have to make div .A
a parent of div .B
and div .C
then set the background
property on B and C to inherit
. This way, B and C (children of A) literally inherit from their parent.
Or, you can make a different class (say "parent") and have div .B
, div .C
and div .A
inherit from div .parent
.
<div class="parent">
<div class="A"></div>
<div class="B"></div>
<div class="C"></div>
</div>
.parent {
background: red;
}
.A {
background: black; /* let's change this for the sake of being rogue */
}
.B, .C {
background: inherit; /* will inherit "red" from .parent */
}
Upvotes: 2