Skip to main content
Version: 1.2.x

Contrast

@use "@glsass/tools/tools.contrast" as contrast;

luminance()

Since v1.1.0

Used in the contrast ratio calculation, the relative luminance (or brightness) is a value in a colorspace, normalized to 0 for darkest black and 1 for lightest white. More information is available on the WCAG website.

contrast.luminance($color);

$value: contrast.lumniance(red);
// Returns 0.2126

ratio()

Since v1.1.0

From two colors, this function calculate the constrast ratio, exprimed as a number.

You can test by yourself some combination with these tools: contrast-ratio.com and color.review.

contrast.ratio($color1, $color2);

contrast.ratio(#02aab0, #fff);
// Returns 2.85

contrast.ratio(#02aab0, #000);
// Returns 7.38

color()

Since v1.1.0

This function returns a color that ensure a minimal contrast ratio 4.5:1, following the WCAG recommandation (and the algorithm provided).

contrast.color($color, $dark: $g-color-black, $light: $g-color-white, $ignore-warning: false);

color: contrast.color(red);
// Returns #000

color: contrast.color(blue);
// Returns #fff

palette()

Since v1.1.0

The palette() function works similary to the color(), but instead of using white and black as main colors, it will first check inside the palette variant.

contrast.palette($color, $varation: "base");


color: contrast.palette(primary);
// Returns #000

color: contrast.palette(primary, 800);
// Returns #89fafe => primary-100, the contrast is 6.7:1, enough > 4.5

color: contrast.palette(primary, 100);
// Return #013d3f => primary-900, better contrast ratio with 9.8:1

swatch()

Since v1.1.0
caution

This function is still experimental, be careful if you want to use it.

This function is similar to color() and palette() ones, but go further. It the color is limited to return a "black" or "white" color, and palette following the variant available, swatch() works a little differently.

To calculate the better color, it will use the HSL model. It will keep same hue and saturation, and change only the lightness to find the better choice.

Thus, it may never return #000 or #fff, but always a color which looks like to be inside the color scheme.

contrast.swatch($color);

color: swatch(cv(primary)); // #02aab0
// Returns #013637 => Check it here: https://color.review/check/013637-02AAB0
// If you use the `palette()` function, it will return #000 because
// the primary-900 wouldn't give a sufficient ratio

color: swatch(red);
// Returns #330000
note

In the last example, swatch(red) returns #330000 (or `rgb(51, 0, 0)) as result, but the first value which will be "acceptable" is #370000/rgb(55, 0, 0).

But in the loop logic, the lightness is increment by +/-1. So the color #370000, equal to hsl(0, 100%, 10.8%), isn't tested.

It's a little compromise to avoid a too complexe/heavy loop to find the color that meets the requirements and follow browsers behavior which also cast it into an integer).