Sass Fundamentals

Writing Sass Functions

Sass Fundamentals

Check out a free preview of the full Sass Fundamentals course

The "Writing Sass Functions" Lesson is part of the full, Sass Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Mike demonstrates writing functions in Sass.

Preview
Close

Transcript from the "Writing Sass Functions" Lesson

[00:00:00]
>> Mike: And we're gonna go over the last topic of the day which is writing our own Sass functions. This is the most advanced we're going to get into the Sass world. So the function declaration lets us define things that take in values in a similar way that we're used to seeing mix ins receive arguments.

[00:00:25]
Except that this has a return declaration that lets us return a value based on the calculation of the inputs and potentially bringing globals into it as well, right? So if there were a global variable, like in this case. I've got w, I might use that inside double, I totally could.

[00:00:46]
In this case I'm not. In this case this is like a pure function. The outputs are strictly expressed in terms of inputs. And you see here you get the expected result. So here I can define my own function. This one's a little pointless cuz I could just do 2x next to both of these width usages.

[00:01:05]
Or next to the one on the bottom, I should say. But let's look at another one. So this I've made up something that's a little bit convoluted but interesting. So I tried to make something that would find the biggest color channel of a color and then give you back something that had that same channel value on the maximum one and then reduce the other two to 0.

[00:01:29]
So if you give me something with a lot of blue in it, I would give you something that had the same blue value, with red and green to zero. So you can see, I use the SASS color functions red, green, and blue to extract the color channels. Then I use if to try to find if we're in a situation where r is the biggest or g is the biggest, otherwise I assume blue is the biggest.

[00:01:52]
And I return a color with that highest channel value and the other two channels at zero. And the way you could use this is the same way we've been using our Sass functions that come with the library itself. And so here, I'm passing in a blue, something that has a lot of red in it and then a green.

[00:02:12]
And you can see if you can read the SASS values here, you can see that it ends up creating something that is only blue, only red and only green with the other two channels being reduced to zero.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now