SASS Recipes: Helping styles help themselves

In the previous SASS recipe post we discussed using loops to create complex series of CSS classes. This week we explore more helper functions tucked away at the SASS Helper Reference

Lighten and Darken

Sometimes when creating accent colors it can be useful to handle it programmatically. lighten() and darken() accept a color and a percentage to increase or decrease that color.

lighten(#000, 20%) => #333333 darken(#ccc, %44) => #5c5c5c 

Lightness

When passed a color, either hexademic prefixed with # or a standard color string, return that color’s lightness as a percentage between 0% and 100%. Be sure to pass your color with the # prefix of you’ll get a syntax error.

lightness(#ccc) => 80% lightness(#d17b7f) => 65.098% lightness(abcabc) => 'SyntaxError: "abcabc" is not a color for `lightness'' 

Putting it to use

So now we’ve got a lightness percentage, what can we do with it? How about automatically adjusting colors based on the background color of a button, like so:

=btn-color($gradientStart, $gradientEnd, $innerShadow)   +vertical-gradient($gradientStart, $gradientEnd)     @if lightness($gradientStart) > lightness(#aaaaaa)     color: #4a4a4a     +text-shadow(0 1px 0 rgba(#fff, .4))   @else     color: #fafafa     +text-shadow(0 -1px 0 rgba(#000, .75))     &:active, &.active     box-shadow: 0 1px 5px $innerShadow inset 

If the lightness of top gradient color ($gradientStart) is lighter than the lightness of a pretty light color (#aaaaaa), then we make our text color dark (#4a4a4a) and give it a white text shadow. If $gradientStart is darker than #aaaaaa, make the text color dark (#fafafa) and give it a light text shadow.

These sorts of things will certainly require tweaking, but the end result are styles that intelligently take care of themselves. Combining our last SASS recipe with these techniques will yield concise yet powerful stylesheets that can be modified solely by editing a list of colors.

Continued tinkering

Be sure to look through the HSL functions of the SASS reference to see all sorts of awesome things you have available. Things like adjusting hue, saturation, converting colors to grayscale, and even getting a color’s compliment are all possible through SASS.

Acknowledgments

Again my thanks go to Ian for his inspiring code which taught me these cool techniques.