Product Design Lessons

Supe Up Your Sass With Mixins

Learn to make processing “methods” in Sass to quickly process variable information into CSS.

Little things matter, and less code is better. To that end we have Sass Mixins: bits of code that give back CSS with one little command. Done right, they can evaluate a bit of information and give you something more useful. In this lesson we'll write a mixin to make text readable on different color backgrounds — even if the background changes.

What mixins do

Mixins "return" information — that is, when you write their name in code, their results will take fill in the blank Here's a basic example:

@mixin doThis() { return 'red' }

This mixin has one job. Everywhere we write "doThis()", Sass will write "red" in CSS. Like so:

Let's look at a more practical example. This next mixin will return white if the background is dark, or black, if the background is light. That automatic contrast is key to ensuring text is readable against its background. Sass has a function to test for lightness — but we need a mixin to judge if the background is light enough for dark text, or vice versa.

1. Create the mixin.

Creating a mixin is easy. Here's the code:

@mixin altColor ( $test-this-color ) { }

That "$test-this-color" between the parenthesis is a variable that the mixin will examine. We don't know what it is, exactly, so we need a test.

2. Set up a test.

The lightness() function determines how far from black a color is. It works on a scale of 0 (black) to 100 (white). Let's say that if $test-this-color is lighter than 60%, then we want dark text. If it's darker than 60%, we want light text.

In Sass we write:

@if ( lightness($test-this-color) > 60% ) { return #000; }

In English: "If the given color is lighter than 60%, then send back #000 (black)."