I have the following CSS
:root {
--primary: #1776BF;
--header-background-color: var(--primary);
}
header {
--primary: #EA5742;
}
header {
position: fixed;
top: 0;
height: 60px;
left: 0;
right: 0;
background-color: var(--header-background-color); //Expecting it to be #EA5742 but it is still #1776BF
}
As far as I have researched, CSS Variable is not meant to be for this type of case. But still, Is there any way to achieve the expected behavior as I mentioned in the comment line of the above code snippet.
CodePudding user response:
If you want --header-background-color
to update is value for header
, then you'll have to redeclare that variable too. Just try re-adding --header-background-color: var(--primary);
below your second --primary
declaration and it will work.
:root {
--primary: #1776BF;
--header-background-color: var(--primary);
}
header {
--primary: #EA5742;
--header-background-color: var(--primary); /* you need to redeclare this variable so that it takes the newly assigned primary value */
}
header {
position: fixed;
top: 0;
height: 60px;
left: 0;
right: 0;
background-color: var(--header-background-color);
}
div { /* this is just an example so you can check the global variable works well too */
position: fixed;
top: 60px;
height: 60px;
left: 0;
right: 0;
background-color: var(--header-background-color);
}
<header>Test</header>
<div>Test</div>
CodePudding user response:
You're right, as var(--xxx) is just replaced by it's value at this time. But why don't you simplify your problematic this way ?
:root {
--primary: #1776BF;
}
body {
background-color: var(--primary);
}
header, anotherelement, yetanotherelement, .aclass {
--primary: #EA5742;
}
header {
position: fixed;
top: 0;
height: 60px;
left: 0;
right: 0;
background-color: var(--primary);
}
<header>test</header>