Nested mixins or functions in SASS

34,393

Solution 1

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

Solution 2

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;
}

Solution 3

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.

Share:
34,393

Related videos on Youtube

iLevi
Author by

iLevi

I don't know what i know

Updated on September 22, 2020

Comments

  • iLevi
    iLevi over 3 years

    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();
    }
    
    • crazyrohila
      crazyrohila about 11 years
      yeah you doing it right. You can call first mixin in second one. check this pen.
    • iLevi
      iLevi about 11 years
      oh, thank you! i tried with this, but isnt working, maybe my ruby is crashing. I will try to re-install. Thank you. (codepen is amazing!, not yet known)
    • Pavlo
      Pavlo about 11 years
      @crazyrohila You should post this as an answer.
    • crazyrohila
      crazyrohila about 11 years
      Sorry I have deleted last pen by mistake. so created a new pen.
    • cimmanon
      cimmanon about 8 years
      It's unclear here why running this code didn't answer your question.
  • dkjain
    dkjain about 7 years
    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'
  • ajax333221
    ajax333221 almost 6 years
    any reason b is not b() in @include b; ?
  • orionrush
    orionrush over 4 years
    @ajax333221 mixins don't HAVE to have parameters, if you don't specify params then the () are optional.