Created
June 22, 2024 12:58
-
-
Save TeamDijon/f829af1e014c58ce5e3b23efc4cbccfb to your computer and use it in GitHub Desktop.
A small snippet that returns the most-contrasted color, given a color
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% comment %} | |
Returns the color code most contrasted with the given color. | |
Accepts: | |
color {Hex color} - The background color of the element. Defaults to #ffffff. | |
black {Hex color} - The first color we calculate the contrast with. Defaults to #000000. (Optional) | |
white {Hex color} - The second color we calculate the constrast with. Defaults to #ffffff. (Optional) | |
Usage: | |
{% render 'color-contrast', color: section.settings.background_color %} | |
Reference: | |
- https://shopify.dev/docs/api/liquid/filters/color_contrast | |
- https://www.w3.org/WAI/WCAG22/quickref/#contrast-minimum | |
{% endcomment %} | |
{% liquid | |
assign color = color | default: '#ffffff' | |
assign black = black | default: '#000000' | |
assign white = white | default: '#ffffff' | |
assign black_contrast = color | color_contrast: black | |
assign white_contrast = color | color_contrast: white | |
if black_contrast > white_contrast | |
echo black | |
else | |
echo white | |
endif | |
%} | |
{% comment %} | |
Explanation for the following example: | |
{% render 'mx-color-contrast', color: '#ff8000', black: '#1f1f1f' %} | |
We have the following colors: | |
color: #ff8000 (some bright orange) | |
black: #1f1f1f (we overwrite the default value) | |
white: #ffffff (default white) | |
That gives the following contrast ratios: | |
black_contrast: 6.5 | |
white_contrast: 2.5 | |
In this case, black is more contrasted than the white color, so we return the black color code. | |
{% endcomment %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment