CSS calc() 将小数转换为像素

CSS calc() convert decimals to pixels

我正在尝试通过 css-scroll-out 脚本提供的变量实现 css 视差效果。 基本上脚本的作用 - 它设置 --viewport-y css 变量,我在计算图像的 top 值时要依赖它。问题是 --viewport-y 值是小数 - 例如0.8610.034

如何从这些值中获取像素值?

我创建了片段来演示我很容易改变不透明度但无法设置 left 属性

的问题

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>

calc 表达式中移动 px,如下所示:

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>

px 可以使用十进制值。但是你使用 calc 单位的方式是错误的。您应该按如下方式进行:

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>

之所以这样工作,是因为您可以在 calc 中混合使用不同的单位。例如 calc(100% - 10px).