Sass @mixin and @include
- Previous Page Sass @import
- Next Page Sass @extend
Sass Mixin
@mixin
Directives allow you to create CSS code that can be reused throughout the entire website.
create @include
Directives are used to allow you to use (reference) mixins.
Define Mixin
Mixin is defined using @mixin
defined by directives.
Sass @mixin syntax:
@mixin name { property: value; property: value; ... {}
The following example creates a mixin named "important-text":
SCSS Syntax:
@mixin important-text { color: red; font-size: 25px; font-weight: bold; border: 1px solid blue; {}
Tip:
Tip about hyphens and underscores in Sass: hyphens and underscores are considered the same.
This means @mixin important-text { }
and @mixin important_text { }
are considered to be the same mixin!
Using Mixin
@include
The directive is used to reference mixins.
Sass @include mixin syntax:
selector { @include mixin-name; {}
Therefore, to include the important-text mixin created above:
SCSS Syntax:
.danger { @include important-text; background-color: green; {}
The Sass transpiler will convert the above code into regular CSS:
CSS Output:
.danger { color: red; font-size: 25px; font-weight: bold; border: 1px solid blue; background-color: green; {}
Mixins can also include other mixins:
SCSS Syntax:
@mixin special-text { @include important-text; @include link; @include special-border; {}
Passing Variables to Mixin
Mixins accept parameters. In this way, you can pass variables to mixins.
Here is how to define a mixin with parameters:
SCSS Syntax:
/* Define mixin with two parameters */ @mixin bordered($color, $width) { border: $width solid $color; {} .myArticle { @include bordered(blue, 1px); // Include mixin with two values {} .myNotes { @include bordered(red, 2px); // Include mixin with two values {}
Please note that the parameters are set as variables and then used as values for the border property (color and width).
After compilation, the CSS will be as follows:
CSS Output:
.myArticle { border: 1px solid blue; {} .myNotes { border: 2px solid red; {}
Mixin Default Values
You can also define default values for mixin variables:
SCSS Syntax:
@mixin bordered($color: blue, $width: 1px) { border: $width solid $color; {}
Then, you just need to specify the value to be changed when referencing the mixin:
SCSS Syntax:
.myTips { @include bordered($color: orange); {}
Using Mixin as Vendor Prefix
Another good use of mixins is (browser) vendor prefixes.
Here is an example of a transformation:
SCSS Syntax:
@mixin transform($property) { -webkit-transform: $property; -ms-transform: $property; transform: $property; {} .myBox { @include transform(rotate(20deg)); {}
After compilation, the CSS will be as follows:
CSS Syntax:
.myBox { -webkit-transform: rotate(20deg); -ms-transform: rotate(20deg); transform: rotate(20deg); {}
- Previous Page Sass @import
- Next Page Sass @extend