29

Some body know how can i use nested mixins or functions in SASS? I have something like this:

@mixin A(){
    do something....
}

@mixin B($argu){
    @include A();
}
iLevi
  • 936
  • 4
  • 10
  • 26

3 Answers3

24

yeah you already doing it right. You can call first mixin in second one. check this pen http://codepen.io/crazyrohila/pen/mvqHo

crazyrohila
  • 616
  • 4
  • 9
12

You can multi nest mixins, you can also use place holders inside mixins..

@mixin a {
  color: red;
}
@mixin b {
  @include a();
  padding: white;
  font-size: 10px;
}
@mixin c{
  @include b;
  padding:5;
}
div {
  @include c();
}

which gives out CSS

div {
  color: red;
  padding: white;
  font-size: 10px;
  padding: 5;
}
Ignatius Andrew
  • 8,012
  • 3
  • 54
  • 54
  • 3
    It must be noted that order of mixin is important i.e. if you move `@mixin a{...}` at the bottom of above code, sass generate compile error `Undefined mixin 'a'` – dkjain Feb 09 '17 at 13:19
  • 1
    any reason `b` is not `b()` in `@include b;` ? – ajax333221 Jul 10 '18 at 17:42
  • 4
    @ajax333221 mixins don't HAVE to have parameters, if you don't specify params then the () are optional. – orionrush Sep 26 '19 at 16:33
4

As mentioned in the other answers, you can include mixins in other mixins. In addition, you can scope your mixins.

Example

.menu {
  user-select: none;

  .theme-dark & {
    color: #fff;
    background-color: #333;

    // Scoped mixin
    // Can only be seen in current block and descendants,
    // i.e., referencing it from outside current block
    // will result in an error.
    @mixin __item() {
      height: 48px;
    }

    &__item {
      @include __item();

      &_type_inverted {
        @include __item();

        color: #333;
        background-color: #fff;
      }
    }
  }
}

Will output:

.menu {
  user-select: none;
}

.theme-dark .menu {
  color: #fff;
  background-color: #333;
}

.theme-dark .menu__item {
  height: 48px;
}

.theme-dark .menu__item_type_inverted {
  height: 48px;
  color: #333;
  background-color: #fff;
}

Scoping mixins means that you can have multiple mixins named the same in different scopes without conflicts arising.

Frederik Krautwald
  • 1,782
  • 23
  • 32