Skip to content

Instantly share code, notes, and snippets.

@TeamDijon
Created June 22, 2024 12:58

Revisions

  1. TeamDijon created this gist Jun 22, 2024.
    46 changes: 46 additions & 0 deletions color-contrast.liquid
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    {% 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 %}