Unable to overwrite CSS variable with its own value
As commented above, CSS is not C++ and you are having a cyclic dependency wanting to express a property with the same property which will not work.
Refering to the specification:
Custom properties are left almost entirely unevaluated, except that
they allow and evaluate the var() function in their value. This can
create cyclic dependencies where a custom property uses a var()
referring to itself, or two or more custom properties each attempt to
refer to each other.
A common fix to that situation is to add more variables to avoid any cyclic dependency.
:root {
--bs:50px;
--bl:16px;
--box-size:var(--bs);
--box--larger:var(--bl);
}
.box {
width: var(--box-size);
height: var(--box-size);
border: 1px solid red;
}
.box--larger {
--box-size: 66px;
}
.box--larger1 {
--box-size: calc(var(--bs) + var(--bl));
}
.box--larger2 {
--box-size: calc(50px + var(--bl));
}
<div class="box">1</div>
<div class="box box--larger">2</div>
<div class="box box--larger1">3</div>
<div class="box box--larger2">4</div>
Overriding :root CSS variables from inner scopes
This is a scoping issue. The way you're doing it, you're inheriting --orange
from the :root
, and --orange
in the :root
has a lightness of 68%.
In order to change it, you'll want to re-scope the --orange
variable to an element that will look up the new --lightness
value. There's a few ways to pull this off:
Option 1: duplicate the --orange
variable on the element:
:root {
--lightness: 68%;
--orange: hsl(255, 72%, var(--lightness));
}
.card {
background: var(--orange);
--orange: hsl(255, 72%, var(--lightness));
}
.card:hover {
--lightness: 45%;
}
<div class="card">
Hello world
</div>
Can a CSS variable be used in the recalculation of its own value?
A quick check on the MDN docs unfortunately did not shine light on this. So unless you're willing to dive into the spec, here's a quick test:
:root {
--x: 4em;
}
.class2 {
--x: calc(0.5 * var(--x));
font-size: var(--x);
}
<div class="class2">
Test - doesn't work as intended
</div>
Related Topics
Set Textfield Height Material-Ui
Hide All Elements Except One Div for Print View
CSS - Opaque Text on Low Opacity Div
How to Set Keyframes Name in Less
CSS Background-Image Refuses to Display in ASP.NET MVC
Bootstrap Collapsed Menu Not Pushing Content Down When Expanded
CSS Positioning Elements Next to Each Other
Grid Layout on <Fieldset>... Bug on Chrome
Queryselector with Nested Nth-Child in Chrome Doesn't Appear to Work
Differencebetween Opacity and That Through Alpha Channel (Rgba)
Remove Underline Only from Anchor Element Child
Why Doesn't This CSS :First-Child Selector Work
Nesting Selectors via Loops with SASS