13

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?

Himmators
  • 14,278
  • 36
  • 132
  • 223

1 Answers1

34

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>
vals
  • 61,425
  • 11
  • 89
  • 138
  • cool, but can this be used togheter with vh, `calc((var(--offset) - 100vh) * 0.0004s)` – Himmators Apr 25 '18 at 11:00
  • 1
    I don't think it can be done. The part of the calc that translates vh into pixels is done inside the properties that handle dimensions, so it's hard to imagine it working in your context. I will think about this and may be I can find some solution – vals Apr 25 '18 at 20:21
  • 1
    I know that your requirements are different, but I have posted the best solution that you can get, AFAIK. – vals Apr 26 '18 at 10:09
  • i'll give you an upvote but it's not really an answer to my question so I can't approve it... – Himmators Apr 26 '18 at 15:12