Search code examples
csscss-variables

CSS calc() convert decimals to pixels


I'm trying to achieve css parallax effect via css-variables privided by scroll-out script. Basically what script does - it sets --viewport-y css variable which I want to rely when calculating top value for image. The problem is --viewport-y values are decimals - e.g. 0.861, 0.034 etc

How do I get pixels value from this values?

I created snippet to demonstrate the issue where I changing opacity easily, but unable to set left property

body {
  --test: 0.5;
}

.container {
  background: yellow;
  width: 100px;
  height: 100px;
  margin: 30px;
  position: absolute;
  opacity: calc( var(--test));
  left: calc( 100 * var(--test))px;
}
<div class="container"></div>


Solution

  • Move px inside the calc expression, like this:

    body {
      --test: 0.5;
    }
    
    .container {
      background: yellow;
      width: 100px;
      height: 100px;
      margin: 30px;
      position: absolute;
      opacity: calc( var(--test));
      left: calc( 100px * var(--test));
    }
    <div class="container"></div>