Sass Functions

Next to variables, Sass functions are perhaps the most useful aspect of the language. We'll look at most of them in this chapter and the next few chapters.

In addition to the functions that Sass provides natively, you can also write your own functions in Ruby. But since this is a Sass course, not a Ruby course, we won't be talking about that here. You'll find full documentation on the Sass Documentation.

You can use standard CSS function syntax to call Sass functions:

SCSS: rgb() Function
p {
   color: rgb(42, 154, 179);
}

which will be output as

CSS:
p {
   color: #2a9ab3;
}

Sass also lets you specify the arguments to the function by their name. Most programming languages refer these as to "named parameters", but the Sass documentation calls these "explicit keyword arguments". Whatever you call them, they can be specified in any order:

p {
   color: rgb($red: 42, $blue: 154, $green: 179);
}

Note that the argument names are prefixed with the dollar sign, the same syntax used to identify variables. Fortunately, the Sass transpiler is smart enough to keep them straight:

SCSS:
#argument {
   color: rgb($red: 42, $green: 179, $blue: 154);
}

#variable {
   $red: 42;
   color: rgb($red: $red, $green: 179, $blue: 154);
}

will be output as:

CSS:
#argument {
   color: #2ab39a;
}

#variable {
   color: #2ab39a;
}

Naming your arguments requires a bit more typing, but it does make your intentions clear, and it eliminates the need to memorize (or look up) the order of parameters.

All the function definitions always use the parameter names in this Sass tutorials, do given the declaration str-insert($string, $insert, $index).

The named parameters (which can be specified in any order) are $string, $insert and $index: str-insert($insert: "hello, ", $string: "world", $index: 1) would return "hello, world".

Sass include various function for string, numeric, list, map, selector and introspection. We will see all these functions in the next few chapters.

Miscellaneous Functions

Sass provides three more functions that don't fit neatly into any of the categories above. Here they are.

Function Description Examples
call($name, $args..) Calls a Sass or CSS function, passing any remaining arguments to the function call(floor, 3, 5, 7, 1)
Result: 1
if($condition, $if-true, $if-false) Returns $if-true if $condition evaluates to true, otherwise returns $if-false. if(1==1, 10px, 20px)
Result: 10px
unique-id() Returns a random unique CSS identifier unique-id()
Result: "utewylqbn"

Learn about string, numeric, list, map, selector and introspection functions in the next few chapters.

Find the full list of Sass functions at the Sass website.