109

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!

rmNyro
  • 303
  • 2
  • 12
clairesuzy
  • 26,108
  • 7
  • 51
  • 51

3 Answers3

224

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;

  }
}
rmNyro
  • 303
  • 2
  • 12
Ryan James
  • 2,241
  • 2
  • 11
  • 2
147

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.

rmNyro
  • 303
  • 2
  • 12
simplethemes
  • 1,912
  • 2
  • 14
  • 11
  • 5
    it does, thank you I had it using `" "` but I like the auto value better :) - didn't need to set variable though I put it in the mixin syntax as the default vaue `@mixin clearfix($width: auto) {...` thank you :) – clairesuzy Mar 29 '11 at 08:07
  • Is any purpose for giving $width:auto; as default value? – Krish Jun 01 '17 at 12:21
12

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;

  }
}
Quentin Veron
  • 2,421
  • 1
  • 10
  • 27