HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
The @mixin directive lets you create CSS code that is to be reused throughout the website
The @mixin
directive lets you create CSS
code that is to be reused throughout the website.
The @include
directive is created to let you
use (include) the mixin.
A mixin is defined with the @mixin
directive.
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: 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!
The @include
directive is used to include a mixin.
Sass @include mixin Syntax:
selector {
@include mixin-name;
}
So, to include the important-text mixin created above:
SCSS Syntax:
.danger {
@include
important-text;
background-color: green;
}
The Sass transpiler will convert the above to normal CSS:
CSS output:
.danger {
color:
red;
font-size: 25px;
font-weight: bold;
border: 1px solid blue;
background-color: green;
}
A mixin can also include other mixins:
SCSS Syntax:
@mixin special-text {
@include
important-text;
@include
link;
@include
special-border;
}
Mixins accept arguments. This way you can pass variables to a mixin.
Here is how to define a mixin with arguments:
SCSS Syntax:
/* Define mixin with two arguments */
@mixin bordered($color, $width) {
border:
$width solid $color;
}
.myArticle {
@include bordered(blue, 1px);
// Call mixin with two values
}
.myNotes {
@include bordered(red, 2px); // Call mixin with two values
}
Notice that the arguments are set as variables and then used as the values (color and width) of the border property.
After compilation, the CSS will look like this:
It is also possible to define default values for mixin variables:
SCSS Syntax:
@mixin bordered($color: blue, $width:
1px) {
border:
$width solid $color;
}
Then, you only need to specify the values that change when you include the mixin:
SCSS Syntax:
.myTips {
@include bordered($color: orange);
}
Another good use of a mixin is for vendor prefixes.
Here is an example for transform:
SCSS Syntax:
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
.myBox {
@include transform(rotate(20deg));
}
After compilation, the CSS will look like this:
CSS Output:
.myBox {
-webkit-transform: rotate(20deg);
-ms-transform:
rotate(20deg);
transform: rotate(20deg);
}