Sass @ mixin provides the facility to reuse the CSS
code. This functionality reduces the amount of code. You can write it once and reference it as per requirement.
Sass mixin can be created very easily by using the
@mixin
followed by its name i.e @mixin HeadingColor
.
@mixin name{
property: value;
property: value;
...
}
@mixin headingText {
color: black;
font-size: 25px;
font-weight: bold;
}
It can be referenced with @include followed by the name of the mixin.
So, to include the headingText mixin created above:
.headingElement {
@include headingText;
}
Source Code
<style>
.headingElement {
color: black;
font-size: 25px;
font-weight: bold;
}
</style>
A mixin can also accept the argument. Let us understand it.
/* Define mixin with two arguments */
@mixin Elementbordered($color, $width,$borderStyle) {
border: $width $borderStyle $color;
}
.main-container{
@include bordered(blue, 1px,solid);
}
.centeredContainer {
@include bordered(red, 2px,dotted);
}
After transpilation, the CSS code will be:
Source Code
<style>
.main-container {
border: 1px solid blue;
}
.centeredContainer {
border: 2px dotted red;
}
</style>
Let us define a default value for mixin.
//mixing statement
@mixin Outerbordered($color: blue, $width: 1px,$style:solid) {
border: $width $style $color;
}
.container{
@includeOuterbordered($color:grey);
}
After transpiling the above sass code, the output CSS will be:
Source Code
<style type="text/css">
.container {
border: 1px solid grey;
}
</style>
Let us see the mixin vendor prefix features.
//scss syntax
@mixin borderRadius($value) {
-webkit-border-radius: $value;
-ms-border-radius: $value;
border-radius: $value;
}
Let us include the above mixing code.
.customBox {
@include borderRadius(10px);
background-color:lightgrey;
padding:10px;
}
After transpiring the above sass code, the resultant CSS code will be.
Source Code
<style type="text/css">
.customBox {
-webkit-border-radius: 10px;
-ms-border-radius: 10px;
border-radius: 10px;
background-color:lightgrey;
padding:10px;
}
</style>