brightness_difference¶
The brightness_difference filter calculates the numerical difference in perceived brightness between two colors. This filter is useful when you need to assess the contrast between colors, particularly in situations where you want to ensure readability or create a specific visual effect.
Functionality
- Color Values: Takes two string arguments representing colors in Hex, RGB, or HSL format.
- Brightness Calculation:
- Converts both colors to the RGB color space.
- Calculates the perceived brightness of each color using the standard formula:brightness = (0.299 * R) + (0.587 * G) + (0.114 * B) where R, G, and B are the red, green, and blue components, respectively.
- Subtracts the brightness of the second color from the brightness of the first color.
- Output: Returns an integer value representing the brightness difference.
- A positive value indicates the first color is brighter.
- A negative value indicates the second color is brighter.
- Zero indicates the colors have the same brightness.
Syntax
Arguments- color2: A string representing the second color for comparison.
Code Samples
Example 1: Comparing Brightness
<!-- Does nothing because white is very bright -->
{{ "#FFFFFF" | brightness_difference: "#000000" }}
{{ "#808080" | brightness_difference: "#808080" }}
{{ "#333333" | brightness_difference: "#AAAAAA" }}
{% assign background_color = "#222222" %}
{% assign backgroun_difference = background_color | brightness_difference: "#FFFFFF" %}
{% if backgroun_difference < -128 %}
{% assign text_color = "#FFFFFF" %}
{% else %}
{% assign text_color = "#000000" %}
{% endif %}
<p style="background-color: {{ background_color }}; color: {{ text_color }};">
This text should be readable.
</p>
This will generate an HTML paragraph with a dark gray background and white text.
Outliers and Special Cases¶
- Invalid Input: If either color input is invalid or in an unsupported format, the filter might return
nil(null) or an error. - Large Differences: The absolute value of the output can be as high as 255, indicating a significant brightness difference between the two colors.
Key Points¶
- The
brightness_differencefilter provides a quantitative way to assess contrast between colors. - It is useful for ensuring text is readable against a background, choosing complementary colors, or creating visual hierarchies in design.
- Remember that the calculated difference is a relative value and may not perfectly align with human perception in all cases.