SASS Mixins are used for writing reusable styles, similar to functions in programming languages. You can define a block of styles inside a mixin and reuse it across your project. Mixins can also accept arguments, which allows for dynamic values, making your code flexible and easier to maintain.
Mixins are defined using the @mixin directive and are included in your styles using the @include directive. You can create mixins with or without arguments, depending on your requirements.
Mixins without Arguments
When you don’t need to pass different values to the mixin, you can use mixins without arguments. These are useful when you want to reuse a fixed set of styles multiple times throughout your project.
Syntax:
@mixin block-name{
property-1: value;
property-2: value;
...
property-n: value;
}
block-name2{
@include block-name;
}
SCSS file:
@mixin first-mixin {
width: 100%;
overflow: hidden;
color: gray;
}
@mixin second-mixin {
@include first-mixin;
ul {
list-style-type: none;
}
li {
display: inline-block;
width: 100px;
padding: 5px 10px;
}
li a {
text-decoration: none;
}
}
navigationbar {
@include second-mixin;
}
Compiled CSS file:
navigationbar {
width: 100%;
overflow: hidden;
color: gray;
}
navigationbar ul {
list-style-type: none;
}
navigationbar li {
display: inline-block;
width: 100px;
padding: 5px 10px;
}
navigationbar li a {
text-decoration: none;
}
To define mixin: @mixin name_of_mixin {...}
To use mixin in the current block: @include name_of_mixin; .
Mixins with Arguments
When you need to reuse styles but with different values, you can use mixins with arguments. This allows you to pass different values (like width, color, etc.) to the mixin, making it more flexible.
Syntax:
// Here default values are optional
@mixin block-name($parameter1, $parameter2: default, ...) {
property-1: $parameter1;
property-2: $parameter2;
// You can use all the parameters
// same as variables
}
block-name2 {
@include block-name($argument1, $argument2, ...);
}
SASS file:
// Here blue is default value of $three
@mixin first-mixin($one, $two, $three: blue) {
width: $one;
overflow: $two;
color: $three;
}
@mixin second-mixin($one, $two, $three, $four) {
// Don't need to pass the third argument if
// the default value is same as your argument.
@include first-mixin($one, $two /*, Default*/);
ul {
list-style-type: none;
}
li {
display: inline-block;
width: $four;
padding: 5px 10px;
}
li a {
text-decoration: none;
}
}
navigationbar {
@include second-mixin(100%, hidden, blue, 100px);
}
Compiled CSS file:
navigationbar {
width: 100%;
overflow: hidden;
color: blue;
}
navigationbar ul {
list-style-type: none;
}
navigationbar li {
display: inline-block;
width: 100px;
padding: 5px 10px;
}
navigationbar li a {
text-decoration: none;
}
To define mixin: @mixin name_of_mixin (arguments...) {...}
To use mixin in the current block: @include name_of_mixin (arguments...);