Introduction
The directives provide the ability to include styles if certain conditions are met. Mixin is a reusable piece of code that allows us to group CSS declarations.
Writing a piece of code repeatedly can be tiring and useless, especially when working on large projects and having better technologies in hand. E.g., If we want to add a button with different button sizes, we can pass different arguments to a button size mixin that will format the variables passed into a valid CSS.
In this blog, we will discuss mixin directives in sass and how they can be beneficial in web development.
Mixin Directives
The mixin directive is a way to reuse styles across the stylesheet. It can store multiple values, parameters, and call functions to avoid writing repetitive codes. A mixin can contain anything that is allowed in SASS or CSS. They are more potent than @extend directives as we can pass arguments to mixins that will enable us to modify the styles when we use them.
We define mixin using the @mixin directive followed by the mixin's name.
Syntax:
@mixin name{
Content
}
Example:
@mixin button {
font-size: 2em;
padding: 0.7em 1.0em;
text-decoration: none;
color: black;
}
Inside the curly braces of mixin, we define the styles we want to reuse. A mixin can contain anything valid in SASS and CSS, such as parent references or selectors.
Using @mixin Directives
Let’s try to understand how to use mixin in our document to utilize the feature to our advantage. We use the @include directive, which eagles us to include the defined mixin. Let’s try to understand this through a simple example.
Consider the following examples:
Example 1:
We define a mixin with the styles we want to inculcate in our button.
@mixin button {
font-size: 2em;
padding: 0.7em 1.0em;
text-decoration: none;
color: black;
}
We include the mixin name with the @include directive wherever we add this mixin.
.newbutton {
@include button;
}
We have successfully added all the mixin properties in our new button by including the button mixin.
A mixin can include several other mixins, making it easy and less complicated for a user to understand the document.
Example 2:
Given an example where we need to pass different colors keeping all other parameters constant.
@mixin button($base, $hover, $link) {
a {
background: $base;
color: black;
radius: 3px;
margin: 2px;
&:hover {
color: $hover;
}
&:visited {
color: $link;
}
}
}
File.scss
.menu-button {
@include button(blue, pink, blue);
}
.text-button {
@include button(yellow, red, white);
}
After compilation, File.css will look like this:
.menu-button a {
background: blue;
color: white;
radius: 1px;
margin: 4px;
}
.menu-button a:hover {
color: red;
}
.menu-button a:visited {
color: green;
}
.text-button a {
background: yellow;
color: white;
radius: 5px;
margin: 8px;
}
.text-button a:hover {
color: black;
}
.text-button a:visited {
color: grey;
}
We passed colors as variables defined as function parameters in the above example.