Check out a free preview of the full Sass Fundamentals course

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

Mike shows that @if directive takes an expression and uses the styles nested beneath it only if the expression returns anything other than false or null.

Preview
Close

Transcript from the "@if Sass Directive" Lesson

[00:00:00]
>> Mike North: The next exercise is really easy, cuz you guys slog through that one. We're gonna introduce one little concept and then make a small tweak to an older exercise that we completed that will make it really cool. So one of the things that SaaS adds, which is really important in terms of being able to parametrize these things and deal with the kind of mixins that we were working with, is we get a little bit of control flow.

[00:00:29]
We get, essentially, if. If and else, right? I don't actually have an example of an else here. You won't need it for your exercise, but it's just @else immediately following the close brace of an if. And one thing to remember is that this is not something that is evaluated at like when your CSS is read by a browser.

[00:00:53]
This is what is evaluated as you build your CSS out. So like whatever it is, that conditional, that if is figured out and resolved and baked in to regular CSS when you're making your browser consumable style sheet. And in this case, what we're doing is we're saying that if the font size is greater than a certain amount, we're gonna also increase the line height.

[00:01:19]
Because potentially, we've hit some threshold where now we know we need to accommodate some extra space. And so here I'm passing in a pixel value to both places and you can see that line height is only added If that condition meets the required criteria. Now we could have done this a null default value as well.

[00:01:39]
But if you imagine that it was a more complicated set of styles, like if we had five or six different things that need to be conditionally applied, you don't want to have to have null values for all of those. And furthermore, oftentimes, you need to toggle between things.

[00:01:54]
And it starts to get to a point where it's like yes, you could do it that way, but oftentimes, this is gonna be the neater way. And it's also pretty readable. Because anyone who comes across this, it is they may be surprised that it's possible to do this.

[00:02:11]
But they will probably be able to make a reasonable assumption as to what's going on here

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