This shortcode takes in a background color and chooses the text color (light or dark) that provides the best contrast with the background. For example, a pure blue background would result in light text, but a pure yellow background would result in dark text.


The selected text color is returned in the form of a CSS class name, either text-white or text-gray-800. The class names are built into Rock, so you shouldn't need to make any changes to your stylesheets.

The background color input parameter value can be any color format supported by the Lava Color Filters.

The calculations used to find color brightnesses and contrast are based on the foreground/background color contrast test defined in the W3C accessibility evaluation document.

Shortcode Details

Create a new Lava Shortcode with the following details:

  • Name: Contrasting Text Color
  • Tag Name: contrastingtextcolor
  • Tag Type: Inline
  • Description: Returns a CSS class for a text color with sufficient contrast for the specified background color


<pre>{[ contrastingtextcolor bgcolor:'#229' ]}</pre>
    <li><strong>bgcolor</strong> (string, required, default:<code>blank</code>) – The background color to choose a text color for. The color format can be rgb, hex or named.</li>
<p>Possible output values are <code>text-white</code> for dark backgrounds or <code>text-gray-800</code> for light backgrounds.</p>

Shortcode Markup:

{%- capture color -%}
    //- convert color format to rgba
    {%- assign bgcolor = 'rgb(0,0,0)' | Mix:bgcolor,'100%' -%}
    //- calculate the background color brightness
    {%- assign colorParts = bgcolor | Remove:'rgb(' | Remove:'rgba(' | Remove:')' | Split:',' -%}
    {%- assign brightnessR = colorParts[0] | AsInteger | Times:299 -%}
    {%- assign brightnessG = colorParts[1] | AsInteger | Times:587 -%}
    {%- assign brightnessB = colorParts[2] | AsInteger | Times:114 -%}
    {%- assign brightness = brightnessR | Plus:brightnessG | Plus:brightnessB | DividedBy:1000 | AsInteger -%}
    //- choose the text color based on the brightness
    {%- if brightness > 125 -%}
    {%- else -%}
    {%- endif -%}
{%- endcapture -%}
{{- color | Trim -}}


  • bgcolor (blank)

Enabled Lava Commands:

No Lava commands required

Follow Up

Please don't hesitate to leave a comment or hit me up on Rock Chat (@JeffRichmond) if you have questions or find any issues with this recipe.

Change Log

  • 2022-06-02 - Initial version