Skip to content

color_difference

The color_difference filter calculates a numerical representation of the perceived difference between two colors. This filter is useful when you need to determine how visually distinct two colors are, especially in scenarios where you want to ensure sufficient contrast or create harmonious color schemes.

Functionality

  • Color Values: Takes two string arguments representing colors in Hex, RGB, or HSL format.
  • Difference Calculation:
    • Converts both colors to the RGB color space if necessary.
    • Calculates the absolute differences between the corresponding red, green, and blue components of the two colors.
    • Sums these differences to obtain a total color difference value.
  • Output: Returns an integer value representing the total color difference. Higher values indicate greater differences between the colors.

Syntax

    {{ color1 | color_difference: color2 }}

Arguments

  • color2: A string representing the second color for comparison.

Code Samples

Example 1: Comparing Similar Colors

    {{ "#FF0000" | color_difference: "#FF3300" }} 
Output
    51
Example 2: Comparing Different Colors

    {{ "rgb(0, 0, 0)" | color_difference: "rgb(255, 255, 255)" }}
Output
    765
Example 3: Comparing Colors in Different Formats
    {{ "#00FF00" | color_difference: "hsl(120, 100%, 50%)" }}

Output

    0 <!-- both are green -->

Outliers and Special Cases

  • Invalid Input: If either color input is invalid or in an unsupported format, the filter might return nil or an error.
  • Zero Difference: A color difference of 0 indicates that the two colors are identical.
  • Maximum Difference: The maximum possible color difference is 765, which occurs between black and white.

Key Points

  • The color_difference filter provides a simple way to quantify the perceived difference between colors.
  • While not a perfect measure of visual distinction, it can be helpful for making design decisions and ensuring accessibility.
  • Consider using this filter in conjunction with other color filters (e.g., color_brightness) to create more sophisticated color logic in your templates.
  • Remember that the calculated color difference is a relative value and may not perfectly align with human perception in all cases.