Over a million developers have joined DZone.

Using IF Statements In Sass

DZone's Guide to

Using IF Statements In Sass

· Web Dev Zone ·
Free Resource

Code something amazing with the IBM library of open source blockchain patterns. Content provided by IBM.

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 @.

    @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;

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}