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
}

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);
}

The resulting CSS output would be:

.box1 {
  padding: 15px;
}

Lets see the full code:

<html>
  <head>
    <title>Page Title</title>
  </head>
<body>
<nav class="navbar">
  <ul>
    <li>Home</li>
    <li>Store</li>
    <li>Contact Us</li>
  </ul>
</nav> 
</body>
</html>

And our SASS:

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

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

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!

Related Posts:


Tim profile image

A little about me..

Hey, I’m Tim! 👋

I’m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out my Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! 🎉