« Back to Index

[Sass: avoiding @if conditionals]

View original Gist on GitHub

Tags: #sass #if #conditions

Sass avoiding @if conditionals.md

#Ugly Conditionals

Instead of this…

$core: true;
$gutter: 8px;

.block {
    @if $core or $compact {
        margin: $gutter;
    }

    @if $tablet {
        margin: $gutter * 2;
    }

    @if $wide {
        margin: $gutter * 4;
    }
}

…I propose…

$core: true;
$gutter: 8px;

.block {
    margin: _($core_value:    $gutter, 
               $compact_value: $gutter,
               $tablet_value:  $gutter * 2,
               $wide_value:    $gutter * 4);
}

This requires the use of the following function…

@function __($core_value:    inherit, 
             $compact_value: inherit, 
             $tablet_value:  inherit, 
             $wide_value:    inherit) {

    @if $core {
        @return $core_value;
    }

    @if $compact {
        @return $compact_value;
    }

    @if $tablet {
        @return $tablet_value;
    }

    @if $wide {
        @return $wide_value;
    }

    @return inherit; // fallback in case none of the conditionals pass
}

…and because we use ‘named’ arguments it means we can miss out arguments that don’t need a value set, so for example below I’m not passing through the $compact_value

.block {
    border: __($core_value:    1px solid red,
               $tablet_value:  1px solid green,
               $wide_value:    1px solid blue);
}

##Issues?

Well there is potentially one issue and one… concern.

The ‘issue’ would be when you miss an argument (as per the border example above) then having us set inherit on a property might break your CSS if you’ve already set a value on that property somewhere else in your code base.

The ‘concern’ is setting a value of inherit is an extra line of CSS code. But that’s the trade-off between slightly larger compiled code compared to the easier maintenance.