How to Overwrite CSS Variable with Its Own Value

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



Leave a reply



Submit