23Determining Conditions with @if

Similar to @each, there’s another feature called @if that allows us to write conditions in our Sass. This kind of feature is mostly useful when writing what we generally refer to as SassScript, writing reusable mixins and functions for Sass.

Oftentimes when writing a mixin that should be used across projects, we want to react to some variable that is passed in. For instance, if you had a mixin called width, you might want to do nothing if the first argument passed in is less than 0. There are lots of situations where we might want our mixins to act smart and react to the values that we pass in.

After the @if keyword, we can put a statement that will evaluate to true or false. For example, 20 > 10 would evaluate to true. And, "hello" == "world" would evaluate to false. Other common comparators are available, such as == (equal to), != (not equal to), > (greater than), and < (less than).

If the statement is true, whatever is inside the following declaration block will be executed. If the statement is false, then it looks for an @else as the next block to continue trying until it successfully matches. If it runs out of @else blocks, then it doesn’t do anything at all.

In our trite (and nationalistic) example, we have a country color mixin. We want a particular color to show up only for particular countries. So, we have @if at the start, and each following country gets an @else if. The first condition to be satisfied by the variable will be executed, and the following ones will stop.

What To Do...
  • Build a mixin with @if.
    advanced/atif.scss
     
    @mixin​ country_color($​country​) {
     
    @if​ $country == france {
     
    color: blue; }
     
    @else​ if $country == spain {
     
    color: yellow; }
     
    @else​ if $country == italy {
     
    color: green; }
     
    @else​ {
     
    color: red; } }
     
     
    .england {
     
    @include​ country_color(england); }
     
    .france {
     
    @include​ country_color(france); }

    This compiles to:

     
    .england {
     
    color: red; }
     
     
    .france {
     
    color: blue; }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.167.114