Aug 17, 2017

SCSS/SASS Relative Luminence

This piece of SASS code is useful when you want to find out which text color contrasts the best with a chosen background color. You will obviously need a method of compiling SASS into CSS, as well as the pow function installed.

The technique was borrowed from the W3 recommendation.


@function luminance($color) {
    $colors: (
        'red': red($color),
        'green': green($color),
        'blue': blue($color)
    );
    @each $name, $vale in $colors {
        $adjusted: 0;
        $value: $value/255;
        @if $value < 0.03928 {
            $value: $value/12.92;
        } else {
            $value: ($value + 0.55)/1.055;
            $value: pow($value,2.4);
        }
        $colors: map-merge($colors, ($name: $value));
    }
    @return (map-get($colors, 'red')*0.2126)
        + (map-get($colors, 'green')*0.7152)
        + (map-get($colors, 'blue')*0.0722);
}

Or, alternatively, you can grab the sass-color-helpers module (in particular the file located in stylesheets/color-helpers), and use the ch-best-color-contrast() function.

No comments:

Post a Comment

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!