Preserving readability with variable text and background colors in Sass


Sass logo

This is a third post exploring applications for Syntactically Awesome Stylesheets (Sass), the CSS preprocessor that can really turbocharge how you create and modify CSS.

Today we’ll be exploring a function called ensureTextContrast() that lets you rest assured that, across two arbitrary font and background color combinations, the font will be light or dark enough to stand out against the background.

The code

@function ensureTextContrast($text-color, $background-color) {
  /* Checking text lightness difference from accent background */
  $diff: lightness($text-color) - lightness($background-color);

  /* If low brightness difference */
  @if abs($diff) < 15% {

    /* Dark background */
    @if lightness($background-color) < lightness(#aaaaaa) {
      @return lighten($text-color, 30);
    } 

    /* Light background */
    @else {
      @return darken($text-color, 30);
    }
  } 

  /* High enough contrast; @return original color */
  @else {
    @return $text-color;
  }
}

What it does

ensureTextContrast() checks the lightness of text and the background it's on. If the numbers are too similar, the function lightens the text (if it's lighter than the background), or darkens it otherwise, by enough to ensure it stands out.

How to use it

After declaring the function, you can do stuff like this:

/* Let's set background and text colors for a callout box. 
These will be different on different versions of a site or theme.
Here we (or the user) has foolishly set them both to bright red. */
$box-bg: #f00;
$box-text: #f00;

.coloredCallOutBox {
    background: $box-bg;
    color: ensureTextContrast($box-text, $box-bg);
}

ensure text contrast sass functionThe result is pink text on a red background—not necessarily the prettiest thing ever, but certainly better than red on red.

Why it's cool

Functions like this are great when there are variables (in this case, color variables) flying around that could take any value, and you want to stay out of trouble. As a project's complexity and the breadth of potential options increases, you'll be using functions like this quite a bit.

This one, in particular, makes sure that readers can always read your text, no matter who sets the colors and how strange they may be.

Enjoy!

I hope these posts are starting to give you a sense of the power of Sass. And I hope ensureTextContrast(), in particular, can keep you out of the waters of barely readable or invisible text. We'd love to hear your thoughts below!

Leave a Reply

Your email address will not be published.