【问题标题】:CSS calc() convert decimals to pixelsCSS calc() 将小数转换为像素
【发布时间】:2018-11-16 08:43:43
【问题描述】:

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

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

我创建了 sn-p 来演示我轻松更改不透明度但无法设置 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>

【问题讨论】:

  • 使用 % 代替像素?

标签: css css-variables


【解决方案1】:

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>

【讨论】:

    【解决方案2】:

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 2012-12-12
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多