Paulund
2014-07-09 #sass #css

Using IF Statements In Sass

In previous tutorials we were investigating some of the features and benefits you get with using Sass to generate your CSS files. If you haven't tried Sass then I advise you look into using it in your next project, to get information on what's involved with Sass view my article on Getting Started with Sass. We also learnt that you can use loops just like in other programming languages to dynamically create classes for your CSS. In this article we are going to look at using IF statements in Sass. To use IF statements you do this by defining them prefixed with a @.


p
{
    @if 1 + 1 == 2 { border: 1px solid;  }
}

Sass IF Statements This will allow you to create a mixin where you pass in a number of different parameters which can change the outcome of the values for element. The below mixin is something you can apply to any element which you want to make absolute positioned, then you just pass in the values for top, right, bottom and left. We then use the IF statements to see if the parameter has a value, if it hasn't then we just ignore that property. This will allow you to exactly position the element anywhere you want using only the properties that you need to.


@mixin absolute-position($top, $right, $bottom, $left)
{
  position: absolute;

  @if $top != '' {
    top: $top;
  }

  @if $right != '' {
    right: $right;
  }

  @if $bottom != '' {
    bottom: $bottom;
  }

  @if $left != '' {
    left: $left;
  }
}