How to create optional arguments for a SASS mixin?
Last Updated :
31 Jan, 2020
To create optional arguments for a SASS @mixin, the mixin declared must be passed and it should be included.
The following approach will explain clearly.
Syntax:
@mixin function-name($var1, $x:val){
/* stylesheet properties */
}
@include function-name(value, 0);
Approach: Assigning Null in @mixin includes
- We can make an argument of mixin optional by defining its default value that argument isn’t passed by @include.
- Passing null or 0 or no argument passed by @include of mixin led to Optional Arguments.
- Optional arguments has variable name followed by colon and a and a SassScript expression
Example 1: Below example illustrates above approach.
SASS file: style.scss
/* Here $x:5px Optional Arguments*/
@mixin shadowbox($hoff, $voff, $blur, $spread, $color, $x:5px){
-webkit-box-shadow: $hoff $voff $blur $spread $color;
-moz-box-shadow: $hoff $voff $blur $spread $color;
box-shadow: $hoff $voff $blur $spread $color;
border: $x solid $color;
/* null is passed in mixin @include*/
div{
@include shadowbox(0, 8px, 6px, -6px, black, null);
display: block;
}
|
Compiled CSS file:style.css
div{
-webkit-box-shadow: 0 8px 6px -6px black;
box-shadow: 0 8px 6px -6px black;
border: 5px solid black;
display: block;
}
|
Example 2: Below example illustrates above approach.
SASS file: style.scss
/* Here $attach:fixed Optional Arguments*/
@mixin backgroundstretch( $bgsize, $attach:fixed ){
background-attachment: $attach;
background-position: center;
-webkit-background-size: $bgsize;
-moz-background-size: $bgsize;
-o-background-size: $bgsize;
background-size: $bgsize;
}
body {
color:$grey;
font-family: Helvetica, sans-serif;
background-image: url('/img/backimg.jpg');
background-repeat: no-repeat;
/* 0 is passed in mixin @include*/
@include backgroundstretch(cover, 0);
}
|
Compiled CSS file:style.css
body {
color: #919191;
font-family: Helvetica, sans-serif;
background-image: url("/img/backimg.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
}
|
Reference: https://sass-lang.com/documentation/at-rules/mixin#optional-arguments
Share your thoughts in the comments
Please Login to comment...