Introduction to SASS functions

History

Sass has had mixins from the beginning and because they accept arguments, we've all been using them like functions. But when Sass 3.1.0 came out it added a feature that blew that notion apart. Functions. Instead of outputting lines of Sass the way mixins do, functions return a value.

Functions

A function is very similar to a mixin, however the output from a function is a single value. This can be any Sass data type, including: numbers, strings, colors, booleans, or lists.

Here's an example of using a SASS function to provide us with a rem font-size for supported browsers and a px font-size for everything else.

First we need to set some variables.

$base-font-size: 16;
$use-rems: true !default;

I use 16 as 1em = 16px is the browser standard.

Now we can set up our function.

@function font-size($font-size) {
  @return if($use-rems, #{$font-size / $base-font-size}rem, #{$font-size}px);
}

Let's break this down.

The first part is our function name font-size which we pass an argument called $font-size.

The next line is what's key to functions and it works like this.

Everything after @return, suprise suprise, is what's returned when this function is called.

So we're returning the value from our if statement and this works like so:

if($use-rems, #{$font-size / $base-font-size}rem, #{$font-size}px)

To understand this function, you need to understand the if() function. if() is a function mimicing the one-line conditional statement: var = condition ? true : false. The first parameter of the if() function is the condition, the second one is the result if condition is true, and the first one is the value if condition is false.

So here is what we've got going on:

  • Our condition is the variable $use-rems
  • If that condition is true we're then constructing our rem font size with #{$font-size / $base-font-size}rem
  • If false we just return the passed in $font-size argument.

Using this function

So in our SASS file we can call this function like so:

element {  
    font: {
        size: font-size(26);
        weight: bold;
    }
}

Which in it's current state would result in:

element { font-size: 1.625rem; font-weight: bold; }  

If we set the $use-rems variable to false, the same code would produce:

element { font-size: 26px; font-weight: bold; }  

So there you go, a quick introduction to SASS functions and an example to boot.

Let me know what you think in the comments below.