How to use mixins - Part 1

How to use mixins - Part 1

·

2 min read

Table of contents

No heading

No headings in the article.

If you've ever checked the source code of a CSS framework, you might have noticed the use of @mixin statements. Have you ever wondered how mixins work, or how you can incorporate them into your code?

To elaborate, mixins are a Sass utility that allows you to encapsulate styles into a single rule. You define a mixin using the @mixin statement, and then include it in your styles using the @include statement.

(Please refer to the following URL to install the sass on your machine https://sass-lang.com/install)

//_global.scss
// syntax
@mixin <any valid sass identifier>(optional arguments) {
... properties
}
//_global.scss
//example
// creating a mixin to reset the anchor tag style, here updating the two properties of the selector in which this is being used.
@mixin reset-anchor-tag {
   text-decoration: none;
   color: $font-clr;
}
// applying the mixin `reset-anchor-tag` on the anchor tag as follow
a {
    @include reset-anchor-tag;
}

In the example above, the code updates the provided properties regardless of where it is used. Let's examine another example that specifically resets the style of the anchor tag.

//_global.scss
@mixin reset-anchor-tag {
    a {
       text-decoration: none;
       color: $font-clr;
    }
}
// the style will reset, only for the anchor tags inside the p tag
p {
    @include reset-anchor-tag;
}

// to do it globally
@include reset-anchor-tag;

Suppose you need to modify only the color and text-decoration of anchor tags that belong to the .container class, instead of resetting the properties to their default values. How can this be achieved?

To accept parameters, we can update the mixin code as follows. We have added an option to provide a default value, that will be used if no values are provided.

//_global.scss
// here `none` and `$font-clr` are the default values
@mixin reset-anchor-tag($decoration-type: none, $color: $font-clr) {
    a {
       text-decoration: $decoration-type;
       color: $color;
    }
}

//usage
@include reset-anchor-tag;
.container {
    @include reset-anchor-tag(underline, #3c37ff);
}

if we have to change only certain variables, we can pass only those variables instead of passing all of them as follow.

// if you wish to update the color of the tag instead of decoration type, the mixin can be used as follow
.container {
    @include reset-anchor-tag($color: #3c37ff);
}
// in this case, the text-decoration property will be set with their default value and the color variable will be used the value provided here.

While there is much more to discuss on mixins, let's wrap up this blog here. We can explore this topic further in a future blog post. (A quick playground for this discussed code snippet can be found here: https://codepen.io/sanjusm/pen/OJojzZE)

Thanks for reading and until the next time.