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>Services</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: red;
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!
Conclusion
If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
If you enjoyed this article & would like to leave a tip — click here