Table of contents
1.
Introduction
2.
Defining Function
3.
What is the purpose of a function
4.
Naming Functions
5.
Arguments
5.1.
Optional Arguments
5.2.
Keyword Arguments
5.3.
Taking Arbitrary Arguments
5.4.
Taking Arbitrary Keyword Arguments
5.5.
Passing Arbitrary Arguments
6.
@return
7.
Additional Functions
7.1.
Plain CSS Functions
8.
Example Code
9.
FAQs
10.
Key Takeaways
Last Updated: Mar 27, 2024

Function Directives in Sass

Author Ranjul Arumadi
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We can write our functions in Sass and use them in our script context or with any value. The function name and any parameters are used to call the function. We can construct complicated operations on SassScript data with functions, which we can reuse throughout our stylesheet. They make it simple to extract readable abstractions of common formulas and behaviours. In this blog, we are discussing function directives in Sass.

Defining Function

The @function at-rule is used to define functions, which is written as:

 

Syntax:

@function <name>(<arguments...>) { ... }

 

The name of a function can be any Sass identifier. It can only have universal statements and the @return at-rule, which specifies the value as the function call's result. The standard CSS function syntax is used to invoke functions.

 

index.scss

@function pow($base, $exponent) {
  $result: 1;
  @for $_ from 1 through $exponent {
    $result: $result * $base;
  }
  @return $result;
}

.sidebar {
  float: left;
  margin-left: pow(4, 3) * 1px;
}

What is the purpose of a function

To know more about function directives in Sass, we have first to understand the purpose of a function. A function resembles a mixin in appearance and accepts the same types of arguments. A Sass function works differently than a CSS function, despite their identical appearance.  

 

Example function:

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

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

 

A mixin makes our lives easier by reducing the amount of time we spend typing repeating code, whereas a function allows us to remove repeatable logic from our code. For example, we use a function to determine a rem value for a given pixel size in the code above. As a result, the code would be as follows:

h1 { font-size: 2rem; }

 

As we can see, instead of adding styles to an element like a mixin, a function just returns a value that we can use in your stylesheets.

Naming Functions

All Sass identifiers, including function names, treat hyphens and underscores the same. Background-color and background_color are both referring to the same function. This is a relic from the early days of Sass when only underscores were allowed in identifier names. The two were made equal to make migration easier after Sass added support for hyphens to match CSS's syntax.

Arguments

Arguments allow us to change the behavior of functions every time they're called. They are key with respect to function directives in sass. The arguments are supplied as a list of variable names surrounded by parentheses in the @function rule after the function's name. The function must be invoked with the same number of parameters as the number of arguments in SassScript expressions. The associated variables in the function’s body contain the values of these expressions. 

There are no restrictions on the use of trailing commas in argument lists! When restructuring our stylesheets makes it easy to avoid syntax problems.

Optional Arguments

Normally, every argument declared must be passed when a function is included. We can, however, make an argument optional by specifying a default value that will be used if the argument is not given. The same syntax as variable declarations are used for default values: the variable name, a colon, and a SassScript expression. This makes it straightforward to design flexible function APIs that we may use in various ways, both basic and complicated.

 

Example:

@function invert($color, $amount: 100%) {
  $inverse: change-color($color, $hue: hue($color) + 180);
  @return mix($inverse, $color, $amount);
}

$primary-color: #036;
.header {
  background-color: invert($primary-color, 80%);
}

Keyword Arguments

Arguments can be passed by name and location in the argument list when a function is called. This is especially handy for functions with several optional or boolean arguments whose implications aren't immediately evident without a name. Variable declarations and optional arguments use the same syntax as keyword arguments.
 

Example:

$primary-color: #036;
.banner {
  background-color: $primary-color;
  color: scale-color($primary-color, $lightness: +40%);
}

Taking Arbitrary Arguments

A function's ability to take any number of parameters is sometimes advantageous. All extra arguments to that function are supplied to that parameter as a list if the last argument in a @function declaration ends with ‘…’. An argument list is a name for this type of argument.

 

Example:

@function sum($numbers...) {
  $sum: 0;
  @each $number in $numbers {
    $sum: $sum + $number;
  }
  @return $sum;
}

.micro {
  width: sum(50px, 30px, 100px);
}

Taking Arbitrary Keyword Arguments

We can also take arguable keyword arguments from argument lists. The meta.keywords() method takes an argument list and returns any additional keywords as a map from argument names (not including $) to the values of those arguments.

Suppose we don't supply an argument list to the meta.keywords() function, it won't accept any further keyword arguments. This aids callers of your function in ensuring that no parameter names have been misread.

Passing Arbitrary Arguments

The same syntax can give positional and keyword parameters to a function, just like argument lists allow functions to take arbitrary positional or keyword arguments. The list followed by… sent as the last argument of a function call will be handled as additional positional arguments. A map followed by..., on the other hand, will be considered as additional keyword arguments. We can even pass both tests at the same time!
 

Example:

$widths: 50px, 30px, 100px;
.micro {
  width: min($widths...);
}

@return

The @return at-rule specifies the value to use as the function's return value. We can only use it within the body of a @function, and each @function must finish with a @return.
 

When a @return is encountered, the function is immediately terminated, and the result is returned. Returning early can be handy for dealing with edge circumstances or situations when a more efficient technique is available without wrapping the entire function in a @else block.
 

Example:

@use "sass:string";

@function str-insert($string, $insert, $index) {
  // Avoid making new strings if we don't need to.
  @if string.length($string) == 0 {
    @return $insert;
  }

  $before: string.slice($string, 0, $index);
  $after: string.slice($string, $index);
  @return $before + $insert + $after;
}

Additional Functions

Sass has a large core library of built-in functions that are always accessible to use, in addition to user-defined functions. Custom functions can also be defined in the host language using Sass implementations. Of course, we may always use the standard CSS functions (even ones with weird syntax).

Plain CSS Functions

Any call to a function that isn't a user-defined or built-in function is compiled into a simple CSS function (unless it uses Sass argument syntax). The arguments will be converted to CSS and included in the function call without modification. This ensures that Sass supports all CSS functions without requiring new versions to be released each time a new one is added.

 

Example:

@debug var(--main-bg-color); // var(--main-bg-color)

$primary: #f2ece4;
$accent: #e1d7d2;
@debug radial-gradient($primary, $accent); // radial-gradient(#f2ece4, #e1d7d2)

Example Code

Let us see a sample code to understand function directives. We will need to create three files; an index.html file, a style.css file and a style.scss file.

 

index.html

<html>
   <head>
      <title>Sass Example Code</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container" id = "width">
         <h2>Sass is awesome!</h2>
         <p>I love Sass.</p>
      </div>
   </body>
</html> 

 

style.scss

$width1: 5px;
$width2: 5px;

@function change_width($n) {
   @return $n * $width1 + ($n - 1) * $width2;
}

#width { padding-top: change_width(20); }

 

We can instruct Sass to look at the file and update the CSS whenever there is a change in the Sass file. We can do this by running the following command.

 

Command

sass --watch C:\ruby\lib\sass\style.scss:style.css

 

After we execute this, we can see that the style.css file is created automatically with the following contents.

 

style.css

#width {
    padding-top: 95px; 
 }

 

To see the output, open the index.html page in a browser.

 

Output

 

In the output, we can see that the top padding is applied.

FAQs

  1. In Sass, how do we write a function?
    We use the @function directive to build a Sass function. The function's name is then followed by any arguments contained in parentheses. Because a function can only return a value, we must use @return to set the value that the function returns.
     
  2. In Sass, what is the purpose of the @return directive?
    The @return directive in Sass is used to invoke the function's return value. It is part of function directives in Sass.
     
  3. Which are the miscellaneous Functions in Sass?
    There are three miscellaneous functions in Sass. They are:

Function

Description

call($name, $args..) Calls a Sass or CSS function, passing any remaining arguments to the function.
if($condition, $if-true, $if-false) Returns $if-true if $condition evaluates to true, otherwise returns $if-false.
unique-id() Returns a random unique CSS identifier

 

Read Also -  Difference between argument and parameter

Key Takeaways

In this blog, we discussed function directives in Sass. In Sass, we can create our functions and use them in our scripts or with any value. The function name and parameters are used to call the function. We can use the function to remove repeated logic from our code.

 

Arguments enable us to modify the behavior of functions every time they are called. Sass comes with a big built-in library of functions always available to use.

 

If you liked this blog about function directives in Sass, check out Sass- Introduction. Also, check out Sass variables.

Live masterclass