Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using IF Statements In Sass

DZone's Guide to

Using IF Statements In Sass

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

In preview 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;
  }
}

Implementing an Experimentation Solution: Choosing whether to build or buy?

Topics:

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}