Sass Basics: The Function Directive

Originally published at: http://www.sitepoint.com/sass-basics-function-directive/

I recently wrote an article about the basics of Sass, specifically the @mixin directive. In keeping with the theme of highlighting the basics of Sass, this time I will be talking about the @function directive.

What a function does

@function remy($pxsize) {
    @return ($pxsize/16)+rem;
}

h1 { font-size: remy(32);}

A function looks a lot like a mixin, and they both accept the same types of arguments. Although they look similar,a Sass function behaves differently. While a mixin makes our life easier by lessening typing repetative code, a function allows you to strip repeatable logic from your code. For example, in the code above we are using a function to calculate a rem value for a given pixel size. The resulting code would be:

h1 { font-size: 2rem; }

As you can see instead of applying styles to an element like you would with a mixin, all a function does is return a value for use in your stylesheets.

Function or a Mixin

The key to understanding when to use a function versus a mixin is knowing what you want. A mixin is used to create styles that would be a chore to continually write. Using a mixin you could easily write these styles with one line of code. When writing mixins you will be tempted to include calculations.We could have wrote the remy function as a mixin:

Continue reading this article on SitePoint

Please, for the love of God, do not append the unit as a string. This is an extremely bad practice I am trying to eradicate once and for all.

Adding a string to a number in order to give it a unit usually shows a very poor understanding of basic arithmetic. A unit is not just a random string at the end of a number. There are reasons why 5 metres per 5 metres gives you 25 square metres in real life. Sass units do not behave any differently.

To add a unit to a unitless number, either you should add 0 of this unit to the initial number, or multiply it by 1 of this unit. For instance, 42 * 1px or 42 + 0px are two perfectly valid ways to transform 42 into 42px. On the other hand 42 + px is a terrible way of casting the number in a length, because you end up with a string and not an actual number (as long as we stick to Sass data types).

It works exactly the same when you want to make a length (or what else) unitless: you don't slice the value to keep the numerical part. You divide it by 1 of this unit, for instance 42px / 1px. Same story.

More information about this: