Let's say I define a CSS variable --half
to be equal to 50%
.
:root {
--half: 50%;
}
Then I can set the width
of something to be 50%
like this:
.partial {
width: var(--half);
}
So far so good. Let's say that I have a tall
element that I want to fill the viewport vertically:
.tall {
height: 100vh;
}
Great. Finally I want my tall
element to only fill up half the vertical space (i.e. 50vh
) if partial
is used. So I tried this:
.tall.partial {
height: calc(100vh * var(--half));
}
Oops, that doesn't seem to work. It does work if I redefine --half
to equal 0.50
:
:root {
--half: 0.50;
}
But then my width
setting above won't work using the variable by itself.
Question Part A: How can I use a XX%
designation in a CSS calc()
expression and have it be interpreted as the percentage value as a factor in multiplication?
Question Part B: If this can't be done, is there a way I could define the percentage value in terms of the actual value or vice versa, such as the following fictitious definition? (I'd rather not define duplicate, "mirrored" values, one in percentages and one in decimal point values.)
:root {
--half-factor: 0.50;
--half: calc(var(half-factor) * 100)%;
}
If I'm forced to define two separate variables (Part B of the question), it appears I can do this:
:root {
--half-factor: 0.50;
--half: calc(100% * var(half-factor));
}
So that will make my application work and have the values ultimately depend on one value definition (here --half-factor
). But if there is a way to pull off both use cases with a single definition, I'd be interested in knowing it. (I know that I can inline calc(100% * var(half-factor))
instead of using var(--half)
but that's not what I mean by "single definition".)