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?
Defining a Mixin A mixin is defined with the @mixin directive. Tip: A tip on hyphens and underscore in Sass: Hyphens and underscores are considered to be the same. This means that @mixin important-text { } and @mixin important_text { } are considered as the same mixin!
Fundamentally both rules do the same thing - load members inside another module. The main differences is how they handle members. @import makes everything globally accessible in the target file.
@mixin, very similar to a function but the main difference between the two is that mixins output lines of Sass code that will compile directly into CSS styles, while functions return a value that can then become the value for a CSS property or become something that might be passed to another function or mixin.
@mixin is used to group css code that has to be reused a no of times. Whereas the @extend is used in SASS to inherit(share) the properties from another css selector. @extend is most useful when the elements are almost same or identical. The main difference between the two is in their compiled CSS file.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With