BB-8
BB-8

Reputation: 625

SASS mixin that applies some rules when we call it

I would like to create a SASS/LESS mixin that asks if a variable is equal to some value then apply some CSS rules.

@mixin myTest($myVar: $num) {
    @if ($myVar == $num) {
      /* Apply rules if $myVar is set $num - I DO NOT KNOW WHAT SHOULD BE THERE */
    } @else {
      /* Do nothing */
    }
}

And then I would like to use my mixin this way:

$num: 1;

@include myTest(1) {
    h1 {
       color: blue;
       background: red;
    }
}

@include myTest(2) {
    h1 {
       color: yellow;
       background: green;
    }
}

So that only the rules inside parentheses of @include myTest(1) { ... } are applied.

The problem is I dont know how to do that.

Upvotes: 1

Views: 71

Answers (3)

3rdthemagical
3rdthemagical

Reputation: 5350

myTest checks the value of $myVar variable and applies passed css rules via @content - see documentation.

@mixin myTest($myVar: $num) {
  @if ($myVar= $num) {
    @content;
  }
}

$num: 1;

@include myTest(1) {
  h1 {
    color: blue;
    background: red;
  }
}

@include myTest(2) {
  h1 {
    color: yellow;
    background: green;
  }
}

Upvotes: 1

Dirk
Dirk

Reputation: 831

You neeed to use @content inyour mixin to get every thing that was in your mixin to be pushed through

$num: 1;
@mixin myTest($myVar: $num) {

    @if ($myVar == $num) {
      /* Apply rules if $myVar is set $num - I DO NOT KNOW WHAT SHOULD BE THERE */
      @content; // this is how you get it in here
    } @else {
      /* Do nothing */
    }
}

@include myTest(1) {
  h1 {
    background:red;
  }
}

@include myTest(2) {
  h1 {
    background:blue;
  }
}

https://codepen.io/anon/pen/YEJKRm

hopes this helps

Upvotes: 0

delinear
delinear

Reputation: 2795

I'm not quite sure I've understood your question fully, but it seems like what you need to do is move your CSS rules inside your mixin:

@mixin myTest($num) {
    @if $num === 1 {
       color: blue;
       background: red;
    } @else {
       color: yellow;
       background: green;
    }
}


$num: 1;
h1 {
  @include myTest($num);
}

Upvotes: 0

Related Questions