开发者

Using Sass, how to convert a percentage to a decimal?

Sass has a percentage() function to convert a unitless number to a percentage but I cannot find a function to do the reverse (percentage to decimal)

I am using the Sass lightness() method to get the hue percentage. I this want to convert this percentage to a decima开发者_如何学Gol value to use in specifying the transparency of a rgba() color.

Here’s a SCSS example which will fail to compile because $transparent-color requires an $alpha value which is a decimal, not a percentage.

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

I’ve been looking for solutions in the Sass Documentation and the Compass Reference and know there must be a way to do this.


You can use Sass math to convert a percentage to a decimal value by dividing the percentage by 100%.

When you divide a percentage by a percentage, the result is a decimal.

Sass code:

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

Compiled to CSS:

.foo { opacity: 0.44; }


While SASS doesn't provide this as a built-in function you could certainly add a custom function to perform the conversion. Taking a look at the source for percentage(), I took a stab at what a decimal() function would look like:

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


here's @Rhysyngsun ruby script as a scss function:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜