Syntax for if/else condition in SCSS mixin

ConditionalMixinsSassIf Statement

Conditional Problem Overview


Hi I'm trying to learn SASS/SCSS and am trying to refactor my own mixin for clearfix

what I'd like is for the mixin to be based on whether I pass the mixin a width.

thoughts so far (pseudo code only as I will be including other mixins)

@mixin clearfix($width) {

   @if !$width {

  	// if width is not passed, or empty do this

   } @else {
 
        display: inline-block;
        width: $width;
   }
}

here's how I thought I might call it, but it's not working.

@include clearfix();

or

@include clearfix(100%)

or

@include clearfix(960px)

I'd appreciate any help on the best or right way to do this!

Conditional Solutions


Solution 1 - Conditional

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Solution 2 - Conditional

You could try this:

$width:auto;
@mixin clearfix($width) {

   @if $width == 'auto' {

    // if width is not passed, or empty do this

   } @else {
        display: inline-block;
        width: $width;
   }
}

I'm not sure of your intended result, but setting a default value should return false.

Solution 3 - Conditional

You could default the parameter to null or false.
This way, it would be shorter to test if a value has been passed as parameter.

@mixin clearfix($width: null) {

  @if not ($width) {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclairesuzyView Question on Stackoverflow
Solution 1 - ConditionalRyan JamesView Answer on Stackoverflow
Solution 2 - ConditionalsimplethemesView Answer on Stackoverflow
Solution 3 - ConditionalQuentin VeronView Answer on Stackoverflow