I'm storing a value in the DOM right now using javascript:
document.documentElement.style.setProperty('--offset', offset+'px')
later on, I use it as a part of a calculation in an animaiton:
@keyframes upanim {
from {transform: translate3d(0,calc(var(--offset) - 100vh ),0);}
to {transform: translate3d(0,0,0);}
}
I now want to use that same value to calculate the speed of that animation, so that the speed is always the same number of pixels/second:
animation: upanim calc(var(--offset) * 0.002)s cubic-bezier(0, 0, 0.25, 1);
The problem is the 'px' and 's', I would like to add the unit inside the calculation instead and just store the value in the DOM. Is this possible?
To use a unitless css variable in a property that needs pixels, you need to multiply it by 1px
width: calc(var(--offset) * 1px);
So, I think that the best that you can get is setting the variable offset with no dimensions, and add this dimensions when used:
In the snippet, hover the body to see the elements moving at constant speed:
#t1 {
--offset: 10;
}
#t2 {
--offset: 20;
}
#t3 {
--offset: 40;
}
.test {
width: 100px;
height: 40px;
margin: 5px;
background-color: antiquewhite;
transform: translateX(calc(var(--offset) * 1vh));
}
body:hover .test {
animation: move calc(var(--offset) * 0.2s) linear forwards;
background-color: lightgreen;
}
@keyframes move {
from {transform: translateX(calc(var(--offset) * 1vh));}
to {transform: translateX(0);}
}
<div class="test" id="t1">ONE</div>
<div class="test" id="t2">TWO</div>
<div class="test" id="t3">THREE</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With