Search code examples
htmlcsscolorssass

How to get the relationship between two colors?


We use as our reference a style guide from User Experience team, which usually documents the colour palette in hexadecimal values. For example:

Primary Color : #F27132;
Hover color : #D16605;

Based on these values we need to create our stylesheet(.scss file). scss uses some functions like $lighten, $darken, $saturate, $desaturate etc. Is there any way to convert these hex codes into such relative formats? Something like,

$primary-color : #F27132
$hower-color : $darken($primary-color, 20%)

Solution

  • I had the same question and found no good answer, so I wrote the following code:

    /// Get difference HSL values between two colors 
    /// @param {Color} $color1 - Base color
    /// @param {Color} $color2 - Second color to compare
    /// @param {Bool} $rounded - If returned HSL values must be rounded,
    ///                          if yes final color will not be exactly the same
    /// @return {Debug} - Difference of HSL values between two colors
    @mixin getHslDifference( $color1, $color2, $rounded: false ) {
        /* Get HSL values of colors */
        $hue1: hue($color1);
        $sat1: saturation($color1);
        $lig1: lightness($color1);
        $hue2: hue($color2);
        $sat2: saturation($color2);
        $lig2: lightness($color2);
    
        /* Get hue difference */
        $hueDiff: -( math.div( $hue1, ( $hue2 * 0 + 1 ) )
            - math.div( $hue2, ( $hue1 * 0 + 1 ) ) ); // Strip units
        $hueDiff: if($rounded == true, round($hueDiff), $hueDiff);
    
        /* Get saturation difference */
        $satDiff: -( $sat1 - $sat2);
        $satDiff: if( $rounded == true, round($satDiff), $satDiff );
    
        /* Get lightness difference */
        $ligDiff: -( $lig1 - $lig2 );
        $ligDiff: if( $rounded == true, round($ligDiff), $ligDiff );
    
        @debug "Increase hue by " + $hueDiff;
        @debug "Increase saturation by " + $satDiff;
        @debug "Increase lightness by " + $ligDiff;
    }
    
    // 1 - Set the primary color value
    $primary-color: #F27132;
    
    // 2 - Get the relationship HSL values between primary and hover colors
    @include getHslDifference( $primary-color, #D16605 );
    
    // Will output:
    // Debug: Increase hue by 8.8419117647
    // Debug: Increase saturation by 7.2537083083%
    // Debug: Increase lightness by -15.2941176471%
    
    
    // 3 - Set the hover color value dynamically (now you can delete previous step
    // hexadecimal value of hover color is no more needed)
    $hover-color: hsl(
        hue($primary-color) + 8.8419117647,
        saturation($primary-color) + 7.2537083083%,
        lightness($primary-color) + -15.2941176471%
    );
    
    @debug $hover-color; // Debug: #d16605