Sass - Mixin Arguments



Description

The SassScript values can be taken as arguments in mixins, which are passed when mixin is included and are available as variable within the mixin. The argument is a name of a variable, which is separated by comma while defining a mixin. There are two types of arguments such as −

  • Keyword Arguments
  • Variable Arguments

Keyword Arguments

Explicit keyword argument can be used to include in mixins. The arguments, which are named can be passed in any order and the default values of argument can be omitted.

For instance, create one SASS file with the following code −

@mixin bordered($color, $width: 2px) {
   color: #77C1EF;
   border: $width solid black;
   width: 450px;
}

.style  {
   @include bordered($color:#77C1EF, $width: 2px);
}

The above code will be compiled to the CSS file as shown below −

.style {
   color: #77C1EF;
   border: 2px solid black;
   width: 450px;
}

Variable Arguments

Variable argument is used to pass any number of arguments to mixin. It contains keyword arguments passed to the function or mixin. Keyword arguments passed to the mixin can be accessed using keywords($args) function which return values mapped to String.

For instance, create one SASS file with the following code −

@mixin colors($background) {
   background-color: $background;
}

$values: magenta, red, orange;
.container {
   @include colors($values...);
}

The above code will be compiled to the CSS file as shown below −

.container {
   background-color: magenta;
}

Example

The following example demonstrates the use of arguments in the SCSS file −

argument.htm

<html>
   <head>
      <title> Mixin example of sass</title>
      <link rel = "stylesheet" type = "text/css" href = "argument.css"/>
   </head>

   <body>
      <div class = "style">
         <h1>Example using arguments</h1>
         <p>Different Colors</p>
         <ul>
            <li>Red</li>
            <li>Green</li>
            <li>Blue</li>
         </ul>
      </div>
   </body>
</html>

Next, create file argument.scss.

argument.scss

@mixin bordered($width: 2px) {
   background-color: #77C1EF;
   border: $width solid black;
   width: 450px;
}

.style  {
   @include bordered(2px);
}

You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −

sass --watch C:\ruby\lib\sass\argument.scss:argument.css

Next, execute the above command; it will create the argument.css file automatically with the following code −

style.css

.style {
   background-color: #77C1EF;
   border: 2px solid black;
   width: 450px;
}

Output

Let us carry out the following steps to see how the above given code works −

  • Save the above given html code in argument.htm file.

  • Open this HTML file in a browser, an output is displayed as shown below.

Sass Mixin Directives
sass_mixin_directives.htm
Advertisements