Introduction
The Saas Mixin Directive is a way to reuse styles across the stylesheet. It can store multiple values to avoid writing repetitive codes. It is a powerful SASS directive that can also pass arguments, making it less complicated than other options. We can also create a mixin with a default value to avoid errors that can be further overwritten by passing a value to the variable in the argument.
In this blog, we will understand Sass passing content block to a mixin in complete detail.
Content Blocks
As we know, a mixin can take arguments. It can also take an entire block of styles known as a content block. A mixin declares that it takes a content block by including the @content at-rule in its body. The content block is passed using curly braces ({ }) like any other block in Sass, and it is included in place of the @content rule.
Consider the following example, which explains how the content block is passed in Sass:
Example:
@mixin hover {
&:not([disabled]):hover {
@content;
}
}
.button {
border: 3px solid blue;
@include hover {
border-width: 2px;
}
}
After compilation into CSS it will become:
.button {
border: 3px solid blue;
}
.button:not([disabled]):hover {
border-width: 2px;
}
A content block is lexically scoped, implying that it can only see local variables in the scope where mixin is included. It can’t see any variables defined in the mixin even if they are defined long before the content block is invoked.
A mixin can include multiple @content at-rules, including separately for each @content block.
Passing Arguments to Content Blocks
A mixin can also pass arguments to its content block in the same way it passes arguments to another mixin using @content(arguments...). The content block user can accept arguments by using the @include directive. The argument list for a content block works similar to mixin’s argument list.
If a mixin passes arguments to its content block, it must declare that it accepts those arguments. This means that one should pass arguments by position rather than their name.
Example:
Scss File
@mixin media($types...) {
@each $type in $types {
@media #{$type} {
@content($type);
}
}
}
@include media(screen, print) using ($type) {
h1 {
font-size: 40px;
@if $type == print {
font-family: Roboto;
}
}
}
When transpired, the CSS file will look like this:
@media screen {
h1 {
font-size: 40px;
}
}
@media print {
h1 {
font-size: 40px;
font-family: Roboto;
}
}