A mixin is composed of the following structure:
// A mixin always begins with @mixin keyword. Parameter(s) for the mixin is not required but it will make the mixin more dynamic if added.
@mixin [mixin-name] ([mixin-parameters...]) {
// Logic along with different functions and evaluations can also add a more dynamic dimension to the mixin. It can take advantage of @if @else, @for, @each, or @while.
[Mixin logic/Sass functions/CSS rules]
// The end result of the mixin is a return of property and value that will output to the stylesheet
[property]:[value];
}
The purpose of a mixin is to create a series of functions that will allow the user to create a robust style based on different circumstances or criteria. Let's examine the add-border
mixin.
@mixin add-border(
$border-position: all,
$border-size: 1px,
$border-pattern: solid,
$border-color: $black) {
@if $border-position == $border-position-all {
border: $border-size $border-pattern $border-color;
}
@else {
border-#{$border-position}: $border-size
$border-pattern $border-color;
}
}
In the case of this mixin, we are trying to add a border to any element that requires it. Our default border is one that will add a 1 pixel solid black border in all directions (top, right, bottom, and left) to an element. However there are times that we will desire a border only in a certain direction/position or a different border style or border color and this is where a mixin can help us, in particular the add-border
mixin.
To include a mixin within a style or element, using the @include
keyword and adding it to an element is the only step needed.
.block {
width: 100%;
padding: 5px;
display: block;
background-color: transparent;
overflow: hidden;
height: auto;
}
.block-border {
@include add-border;
}
The above code will add the default border, a 1 pixel solid black border in all directions (top, right, bottom, and left), to the block-border
style.
One thing to keep in mind, When placing your @include into a CSS selector, it is considered best practice to include the mixin directly after the parent selector as seen in the following example.
Placing the mixin first serves a couple of purposes:
Lets' look at how to use the arguments within a mixin to give us the most advantage and robustness.