08 May 2017

Using lighten() and darken() in SASS

Until recently I didn’t know about the lighten() and darken() functions in SASS. I’ve since found them to be increasingly useful in my component building workflow. As the names suggest, given a colour and percentage, these functions will return a colour lighter or darker respectively.

When are these useful?

These functions are particularly useful when creating the style rules for any web UI component. There is a balance when creating the component’s interface between providing too many parameters and too few, between flexibility and ease of use. lighten() and darken() can help to reduce the required parameters, creating an easier to use component. For example, a button class might use a darker background on hover. Rather than rely on the developer to supply a suitable colour as another parameter, we can handle that from within the component code, as shown in the CodePen example below.

See the Pen Darken via SASS by Martin Falkus (@falkus) on CodePen.

The next developer to come along and use our component only has to supply a single colour and the component updates accordingly in both normal and hover states, which is pretty neat.

Whilst the button example is very simple, a more complex UI could benefit significantly from colours defined relative to a base value. As you’d expect, these functions can be used in place of any ‘normal’ colour in your SASS files, so worth remembering next time you are creating or refactoring a UI component.

Back to posts