DEV Community

Cover image for Functions in SASS Tutorial
Richard Rembert
Richard Rembert

Posted on • Edited on

Functions in SASS Tutorial

Sass functions can receive arguments and return a single value.

They add an element of programming to writing CSS code, and we can now do math!

The standard math operators +, -, *, /, and % can all be utilized.

An Example Function

The following function can accept two arguments, $first-number and $second-number. The value that is returned by the function is the sum of the two variables:

@function add-numbers($first-number, $second-number) {
  @return $first-number + $second-number
}
Enter fullscreen mode Exit fullscreen mode

Say we want to replace the value of a padding property with the sum of two separate values.

We would call our function and pass in the arguments like so:

.box1 {
  padding: add-numbers(5px, 10px);
}
Enter fullscreen mode Exit fullscreen mode

The resulting CSS output would be:

.box1 {
  padding: 15px;
}
Enter fullscreen mode Exit fullscreen mode

Lets see the full code:

<html>
  <head>
    <title>Page Title</title>
  </head>
<body>
<nav class="navbar">
  <ul>
    <li>Home</li>
    <li>Services</li>
    <li>Contact Us</li>
  </ul>
</nav> 
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And our SASS:

@function add-numbers($first-number, $second-number) {
  @return $first-number + $second-number
}

.navbar {
  background-color: red;
  padding: add-numbers(5px, 100px);
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
  }
}
Enter fullscreen mode Exit fullscreen mode

As you can see, functions help you write more readable and DRY Sass, as you can utilize reusable logic in a very efficient manner. This can make a huge difference when you start working on larger and more complex projects!

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

Top comments (0)