The @mixin directive allows for the creation of reusable CSS code segments to be utilized across the website.
The @include directive facilitates the utilization (inclusion) of the mixin.
A mixin is declared using the @mixin directive.
Sass @mixin Syntax:
@mixin name { property: value; property: value; … } |
In the following example, a mixin named “important-text” is established:
SCSS Syntax:
@mixin important-text { color: red; font-size: 25px; font-weight: bold; border: 1px solid blue; } |
Tip: In Sass, hyphens and underscores are treated interchangeably. Therefore, both @mixin important-text { } and @mixin important_text { } are regarded as the same mixin! |
The @include directive is employed to incorporate a mixin.
Sass @include mixin Syntax:
selector { @include mixin-name; } |
Thus, to utilize the important-text mixin established previously:
SCSS Syntax:
.danger { |
The Sass transpiler will transform the above code into standard CSS.
CSS output:
.danger { color: red; font-size: 25px; font-weight: bold; border: 1px solid blue; background-color: green; } |
A mixin can also incorporate additional mixins within its definition.
SCSS Syntax:
@mixin special-text { @include important-text; @include link; @include special-border; } |
Mixins can accept arguments, enabling the passing of variables to a mixin.
Below illustrates how to define a mixin with arguments:
SCSS Syntax:
/* Define mixin with two arguments */ |
Observe that the arguments are defined as variables and subsequently utilized as values (such as color and width) for the border property.
Following compilation, the resulting CSS will resemble this:
CSS Output:
.myArticle { border: 1px solid blue; } .myNotes { border: 2px solid red; } |
You can also specify default values for mixin variables.
SCSS Syntax:
@mixin bordered($color: blue, $width: 1px) { |
In such cases, you’re only required to specify the values that deviate from the default when including the mixin.
SCSS Syntax:
.myTips { @include bordered($color: orange); } |
Another useful application of mixins is for handling vendor prefixes, as demonstrated in the following example for the transform property:
SCSS Syntax:
@mixin transform($property) { -webkit-transform: $property; -ms-transform: $property; transform: $property; } .myBox { @include transform(rotate(20deg)); } |
Upon compilation, the resulting CSS will be structured as follows:
CSS Output:
.myBox { -webkit-transform: rotate(20deg); -ms-transform: rotate(20deg); transform: rotate(20deg); } |