Mixin declares once, and reuse in many places. It contains a group of CSS code, for reusable code
Unlike Sass, There is no keyword and These are similar to functions in a programming language.
It supports the DRY(Don’t Repeat Yourself) principle.
Stylus Mixins
Syntax
Declaring mixin using square braces with
mixin-name([arguments]){
//css code
}
It contains optional arguments. Once declared mixin, use mixin in any place using the below syntax.
You can call directly with and without (). Both behave the same.
It copies the code from the mixin to the place where it is called.
div{
mixin-name([arguments])
or
mixin-name [arguments]
}
arguments are optional.
Mixin accepts with or without arguments
Here is an Mixin without arguments
buttonMixin(){
border-radius:25px;
color:white;
background-color:blue
}
button{
buttonMixin()
buttonMixin
}
Compiles to CSS as follows
button {
border-radius: 25px;
color: #fff;
background-color: #00f;
}
- Mixin with arguments
buttonMixin(widthValue){
border-radius:25px;
color:white;
background-color:blue
width:widthValue
}
button{
buttonMixin(50px) // or
buttonMixin 50px
}
Compiled to CSS
button {
border-radius: 25px;
color: #fff;
background-color: #00f;
width: 50px;
}
Mixin Default arguments values
Sometimes, Mixin can be defined with default values.
If the user does not pass the argument to mixin, it takes the default value
buttonMixin(widthValue=100px){
border-radius:25px;
color:white;
background-color:blue
width:widthValue
}
button{
buttonMixin()
}
mixins are not passed with data, Takes default value
button {
border-radius: 25px;
color: #fff;
background-color: #00f;
width: 100px;
}
If you call mixin with argument, It overrides the default value and sets to it
.button1{
buttonMixin(50px)
}
Generated CSS
.button1 {
border-radius: 25px;
color: #fff;
background-color: #00f;
width: 50px;
}
Mixin REST Parameters
REST parameters are also called variable arguments using args... syntax.
Mixin with variable arguments accepts dynamic arguments.
sometimes, border or box-shadow contains multiple values to be passed a single argument
buttonMixin(border1...){
border-radius:25px;
color:white;
background-color:blue
width:50px;
border:border1;
}
.button1{
buttonMixin 2px solid red;
}
Generated CSS
.button1 {
border-radius: 25px;
color: #fff;
background-color: #00f;
width: 50px;
border: 2px solid #f00;
}
Mixins blocks
Mixins also pass a block of CSS code.
First, Mixin is declared as below. It contains {block} which copy the block of code
mymixin()
.heading1
{block}
.heading2
{block}
Mixin is called with + plus symbol and name by passing block of css code.
+mymixin()
width: 50px
color:blue;
Generated CSS
.heading1 {
width: 50px;
color: #00f;
}
.heading2 {
width: 50px;
color: #00f;
}