godblessstrawberry
godblessstrawberry

Reputation: 5068

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>

Upvotes: 5

Views: 5151

Answers (2)

str
str

Reputation: 45019

Using decimal values for px is perfectly fine. But the way you are using calc with units is wrong. You should do it as follows:

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>

The reason it works like that is that you can mix different units within calc. For example calc(100% - 10px).

Upvotes: 3

D&#225;niel Kis-Nagy
D&#225;niel Kis-Nagy

Reputation: 2505

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>

Upvotes: 7

Related Questions