Using functions with SCSS

Did you know you could write functions in SCSS, much like you would with Javascript? Neither did I until recently. I was so blown away by this, that I thought I’d share my findings.

To write a new function, we simply go into our.scss file and set one up like I have below. Much like in Javascript, you just need the function name, the various params, and whatever you expect to be returned.

@function function-name($param1, $param2, ...) {
    @return whatever-value-you-expect-here;

As an example, let’s create a function that takes in a value from the param pixelSize, perform a very basic calculation, and then output a value with which we can use in our class. This will convert the pixelSize to a rem value, and append the string rem to the end, so we don’t need to do anything more when we call our function.

@function someCalculation($pixelSize) {
    @return ($pixelSize/16)+rem;

h1 { 
  font-size: someCalculation(32);

As you can see above, passing 32 into the function will convert it to 2. While this a very generic example, you could create a function that allows you to apply various values based on the size of the users screen. Pairing a function with mixins and the various tools at your disposal from SCSS will make your code a lot more powerful. If you would like to read more on this topic, I have attached the link to the documentation below.

If you would prefer to watch a video on the topic, here is the link to one of Travery Medias video, which I find to be top notch and very easy to understand.

If you have any questions on the topic, let me know in the comments below or reach out on my social media accounts. Thank you, and have a wonderful day!

Leave a Reply