Sass is a CSS preprocessor and whether using it as SCSS or Sass itself, it’s incredible. It lets us do more with CSS and makes complex CSS tasks easy. Mixins in Sass are exceptional and valuable to speed up development. This article will introduce you to how Sass Mixins work.
What are Sass Mixins?
According to the official Sass website, “Mixins allow you to define styles that you can reuse throughout your stylesheet”. In other words, Mixins are reusable blocks of code that you can write your CSS styles in and use throughout your entire stylesheet.
Benefits of using Sass Mixins
- They prevent the repetition of code
- They make the stylesheet less crowded
- They help reduce the size of the stylesheet file
Creating a Mixin
Creating a mixin is straightforward. All you have to do is use the @mixin
directive followed by the name of the mixin, then open and close curly braces. The @mixin
syntax is shown below:
@mixin name {
// css goes here…
}
Here is an example code to get a better understanding of how it works:
@mixin red-text {
color: red;
font-size: 25px;
font-weight: bold;
border: 1px solid red;
}
The red-text style can be added anywhere in the stylesheet by using the @include
directive to call the @mixin
defined above.
Using a Mixin
Now that you’ve declared your mixin, it’s time for you to learn how you can use them in your SCSS stylesheet. To use a mixin, you simply need to use the @include
directive followed by the mixin's name and a semicolon. The @include
syntax is shown below:
selector {
@include mixin-name;
}
And here is how you will use the mixin defined in the previous section within your selector. Let’s say we have a .text class that we want to style:
.text {
letter-spacing: 1px;
@include red-text;
}
The CSS transpiler will then convert the above code to the following:
.text {
letter-spacing: 1px;
color: red;
font-size: 25px;
font-weight: bold;
border: 1px solid red;
}
You can also have multiple mixins within a selector:
selector {
@include mixin-a;
@include mixin-b;
@include mixin-c;
}
Conclusion
Sass Mixins are simple and powerful. They can help you build faster without repeating yourself and help keep your stylesheet simple. To work with the basics of SCSS Mixins, all you need to understand are:
- The
@mixin
directive for creating the mixins. - The
@include
directive for using the created mixins.
If you have any questions concerning this article or other frontend related topics, do not hesitate to contact me either on Twitter or LinkedIn.
Top comments (0)