【问题标题】:Using Sass, how to convert a percentage to a decimal?使用 Sass,如何将百分比转换为小数?
【发布时间】:2011-11-02 10:24:55
【问题描述】:

Sass 有一个 percentage() function 可以将无单位数字转换为百分比,但我找不到相反的函数(百分比到小数)

我正在使用 Sass lightness() method 来获取色调百分比。我想将此百分比转换为十进制值,以用于指定rgba() 颜色的透明度。

这是一个无法编译的 SCSS 示例,因为 $transparent-color 需要 $alpha 值,它是小数,而不是百分比。

$color: hsl(50deg, 50%, 50%);
$alpha: lightness($color);
$transparent-color: rgba(0,0,0,$alpha);
.foo { background: $transparent-color }

我一直在Sass DocumentationCompass Reference 中寻找解决方案,并且知道一定有办法做到这一点。

【问题讨论】:

    标签: css sass compass-sass


    【解决方案1】:

    您可以使用 Sass 数学通过将百分比除以 100% 来将百分比转换为十进制值。

    当您将百分比除以百分比时,结果是小数。

    Sass 代码:

    $percent: 44%
    .foo
      opacity: $percent / 100%
    

    编译成 CSS:

    .foo { opacity: 0.44; }
    

    【讨论】:

      【解决方案2】:

      虽然 SASS 没有将此作为内置函数提供,但您当然可以 add a custom function 执行转换。查看 percent() 的源代码,我试探了一下 decimal() 函数的样子:

      def decimal(value)
        unless value.is_a?(Sass::Script::Number) && value.unit_str == "%"
          raise ArgumentError.new("#{value.inspect} is not a percent")
        end
        Sass::Script::Number.new(value.value / 100.0)
      end
      

      【讨论】:

      • 感谢 Rhysyngsun!我编辑了您的解决方案以使用“100.0”而不是“100”以确保结果为浮点数。经过测试,它按预期工作。
      【解决方案3】:

      这是作为 scss 函数的 @Rhysyngsun ruby​​ 脚本:

      @function decimal($v) {
          @if (type_of($v) != number OR unit($v) != "%") {
              @error "decimal: `#{$v}` is not a percent";
          }
          @return $v / 100%;
      }
      
      

      【讨论】:

        猜你喜欢
        • 2013-09-01
        • 2017-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多