Sass:HSL颜色代码颜色变暗

时间:2017-06-22 15:23:41

标签: css colors sass

我知道如何使用内置函数从十六进制代码中确定较暗的颜色。但是如何用hsl做到这一点?我有三种颜色,一种是主色,一种是深色,一种是浅色。我需要编写一个函数来计算它们之间的差异,并为它们获得更浅和更暗的阴影。因此,当我添加另一种颜色代码时,它会给出相同百分比的浅色和深色。

据我从Sass文档中了解到,我首先需要一个函数来获得基色的色调,饱和度和亮度,对吧?那么呢?

这些是我的十六进制颜色:

$base: #7760BF;
$base-darker: #483584;
$base-lighter: #b5a9dc;

在这里他们是hsl,以防万一:

$base: hsl(255, 43%, 56%);
$base-darker: hsl(254, 43%, 36%);
$base-lighter: hsl(254, 42%, 76%);

有人能帮助我吗?

1 个答案:

答案 0 :(得分:11)

在Sass中,类型会自动转换。 Sass standard library中的颜色函数将接受任何颜色,rgb或hsl。

首先生成更暗更浅的颜色,您可以使用darkenlighten。我做了一个例子here

enter image description here

然后要知道颜色之间的亮度差异以生成具有相同差异的新颜色,您可以使用lightness

@function get-lightness-diff($base, $color) {
    @return lightness($base) - lightness($color);
}

@function get-variant($color, $diff) {
    @if ($diff < 0) {
        @return darken($color, -$diff);
    } @else {
        @return lighten($color, $diff);
    }
}

@function get-variants($color, $diff) {
    $ret: ();
    $ret: map-merge($ret, ( darker: get-variant($color, -$diff) ));
    $ret: map-merge($ret, ( lighter: get-variant($color, $diff) ));
    @return $ret;
}

@function get-variants-from-set($color, $darker, $base, $lighter) {
    $darker-diff: get-lightness-diff($base, $darker);
    $lighter-diff: get-lightness-diff($base, $lighter);

    $ret: ();
    $ret: map-merge($ret, ( darker: get-variant($color, $darker-diff) ));
    $ret: map-merge($ret, ( lighter: get-variant($color, $lighter-diff) ));
    @return $ret;
}

$base: hsl(255, 43%, 56%);
$base-lighter: hsl(255, 43%, 66%);
$base-darker: hsl(255, 43%, 46%);

// Get a lightness diff, from the light color for example
$diff: get-lightness-diff($base, $base-lighter);

// Variants: contains a map with 'darker' and 'lighter' colors.
$variants: get-variants($base, $diff);
// Or create your lighter/darker variants manually:
$darker: get-variant($base, -10%);
$lighter: get-variant($base, 10%);

// Or all-in-one: create your variants from an other set of colors:
$other-base: hsl(255, 33%, 33%);
$other-variants: get-variants-from-set($other-base, $base-darker, $base, $base-lighter);

我做了另一个例子here,但您可能需要对其进行调整以使其符合您的需求。

Variants

编辑(11/07/17):自从我撰写这篇文章以来,我改进了可用于生成颜色变体的实用程序。您可以在https://codepen.io/ncoden/pen/yXQqpz?editors=1100找到一个示例。