ttyy
ttyy

Reputation: 245

Is it possible to create a local/private sass mixin?

I have three sass files: a.scss, b.scss, c.scss

a.scss:

@mixin font($size, $color){
  font-size: #{$size};
  color: #{$color}
  }

 p{
  @include font(10px, blue)
  }

b.scss:

@mixin font()
{
..
}

c.scss

@import a.scss
@import b.scss

I think the mixin font() in b.scss override the mixin font($size, $color) in a.scss.

p{
  @include font(10px, blue)  // use mixin font() in b.scss, error
  }

Is it possible to create a local/private sass mixin? Or all mixins in sass are global, I have to give them unique name for each mixin?

Upvotes: 17

Views: 10609

Answers (3)

Boogie
Boogie

Reputation: 818

UPDATE: Now with the new @use rule you can add private members just by starting its name with either - or _

More info here: https://sass-lang.com/documentation/at-rules/use#private-members

Upvotes: 7

Jon Fagence
Jon Fagence

Reputation: 180

Mixins within selectors are local to that selector just like Sass variables are. These two mixins are independent of each other:

.foo{
    @mixin my_color(){
        color: #ffcc00;
    }
    @include my_color;
}

.bar{
    @mixin my_color(){
        color: #00ffcc;
    }
    @include my_color;
}

So, to answer your final question - only mixins defined at the global level are global, and you can otherwise reuse names safely. In your example, if your a.scss, b.scss and c.scss are structured to define different overarching classes (eg .header, .main, .footer) you can have local font mixins for each.

Related: Localizing/Scoping a sass mixin.

Upvotes: 14

Jonathon
Jonathon

Reputation: 113

You are right. Just as in a typical CSS file, your sass project is compiled top down. So a mixin sharing the same name as a previous one will overwrite it. If you wish to use the original mixin in c.scss you would have to redefine it.

Upvotes: 1

Related Questions