color_brightness¶
The color_brightness filter calculates the perceived brightness of a color. This filter is useful for determining the contrast between different colors and ensuring readability in various contexts, such as text on a background or design elements.
Functionality
- Color Values: Takes a string representing a color in Hex, RGB, or HSL format.
- Brightness Calculation: Calculates the perceived brightness of the color based on its RGB components using the formula:brightness = (0.299 * R) + (0.587 * G) + (0.114 * B) where R, G, and B are the red, green, and blue components of the color, respectively.
- Output: Returns a numerical value (decimal) representing the brightness. The result ranges from 0 (black) to 255 (white).
Syntax
ArgumentsThe color_brightness filter does not require any arguments.
Code Samples
Example 1: Calculating Brightness of Basic Colors
{{ "#FFFFFF" | color_brightness }}<BR>
{{ "#000000" | color_brightness }}<BR>
{{ "#FF0000" | color_brightness }}<BR>
{{ "rgb(0, 255, 0)" | color_brightness }}<BR>
{{ "hsl(120, 50%, 50%)" | color_brightness }}<BR>
{% assign background_color = "#F0F0F0" %} {# Light gray #}
{% assign text_color = "#333333" %} {# Dark gray #}
{% assign brightness = background_color | color_brightness %}
{% if brightness > 128 %}
<p style="color: {{ text_color }};">This text is on a light background.</p>
{% else %}
<p style="color: white;">This text is on a dark background.</p>
{% endif %}
Output: (Since the background color's brightness is greater than 128)
Outliers and Special Cases¶
- Invalid Input: If the input is not a valid color string, the filter may return an error or an unexpected result. Ensure your input is in the correct format (Hex, RGB, or HSL).
Key Points¶
- The
color_brightnessfilter is a helpful tool for assessing the relative lightness or darkness of a color. - It can be used to determine appropriate text colors for readability based on the background color.
- You can incorporate brightness calculations into more complex color manipulation logic, such as creating color palettes or adjusting contrast.
- It is based on the standard formula for perceived brightness recommended by the W3C.