如果我有原始颜色和变暗的颜色,我如何确定在 Sass 中使用多少百分比将其变暗?

If I have the original color and a darkened color, how do I determine what percentage was used to darken it by in Sass?

Sass 语言有一个名为 darken 的函数,它有两个参数:一种颜色和你想要使颜色变暗的百分比。我只知道原始颜色和结果颜色。如何确定与原始颜色一起传递给变暗函数的百分比值?

darken(#e8e8e8, ???) // returns #c1c1c1

您可以使用 rgba(),其中 rgb 是红色、绿色、蓝色,'a' 是 alpha。您可以使用 alpha 而不是百分比。

对于变暗(也可能变亮),您需要计算两种颜色的亮度值之间的差异:

@function color-difference($c1, $c2) {
  $c1: lightness($c1);
  $c2: lightness($c2);
  @return max($c1, $c2) - min($c1, $c2);
}

$color1: #e8e8e8;
$color2: #c1c1c1;

.foo {
  // guessed the percentage manually
  test: darken($color1, 15.25%);
  // check our percentage
  test: color-difference($color1, $color2);
  // do we get the same result?
  test: darken($color1, color-difference($color1, $color2));
}

输出:

.foo {
  test: #c1c1c1;
  test: 15.2941176471%;
  test: #c1c1c1;
}