Reputation: 280
I'm trying to style the background colour of an element using the background colour belonging to its grandparent, but then set its parent to have a different colour. Is this possible?
I thought that having its parent set to inherit
and then the element set to inherit
to 'cascade' it down would work, and that then I would be free to change the background colour of the parent, but this hasn't worked.
Below is a stripped-down version of what I'm trying to accomplish.
div {
background-color: #e00;
}
span.foo {
background-color: inherit;
}
span.bar {
background-color: inherit;
}
span.foo {
background-color: #777;
}
<div>
<span class="foo">
Hello
<span class="bar">
World
</span>
</span>
</div>
Upvotes: 1
Views: 694
Reputation: 32315
You can't do what you want using CSS, but your question also demonstrates that you have an incorrect idea about how CSS works, so its important to explain why you can't do what you want:
CSS is not a programming language - it does not have a serial model of operations - do this, then do that, like programing languages do.
CSS is a description language - it allows you to describe the properties of objects without a time function. That is - when you say "inherit" in CSS, it does not mean "copy the value and maintain your own copy", it means "this value is exactly like the parent, and it will always be exactly like the patent, even if the parent changes" - because it is not an operation, it's a description of how things are.
Another example, is when you write something like:
p { color: green; }
p { color: red; }
It doesn't mean "draw the text using green color then using red color" - it means "the designer thought that he wants the text green, then decided that red is better - so always draw the text using red".
If you really want to do something like copying the value of another element and then changing the source element, you'd need to use a programming language - though I think it's best if you try to think of a way to get the style that you need by using only CSS's descriptive properties.
Upvotes: 1
Reputation: 1045
you can do it using jquery on page load i.e:
<script>
$(document).ready(function(){
var divColor = $("div").css("background-color");
$(".bar").css("background-color", divColor);
});
</scipt>
Hope this helps.
Upvotes: 0