Hello Sunil
Sass Mixins

Sass Mixins – A Quick Intro

One of the challenges in a developer’s life is speeding up and automating the development process while keeping high-quality standards.

A great solution for front-end developers using Sass is its mixins capability.

First of all, why is it good to use mixins, and how can it help you?

Also Read: Sass Variables – A Quick Intro

You should use mixins because it lets you make groups of CSS declarations that you want to reuse through your website.

Also, you can pass in values to make your mixins more flexible. Mixins are good because they make your code cleaner, and they are in the same file, so you can easily find them.

When you find yourself writing the same code over and over again, it feels like Sass mixins might help you out. Sass mixins are CSS functions that you can include whenever you want.

Today’s article is about Sass mixins, it answers the question of What? Why? and How to use a mixins?

What is mixins in Sass?

A mixin is a block of code that lets us group CSS declarations we may reuse throughout our site.

In our opinion, mixins are the biggest feature from Sass because it allows you to write cleaner code.

Take for example, displaying an HTML element as a flex element.

.row {
    display: flex;
}

There are many elements we want displayed flex, and typing this declaration above over and over gets boring pretty fast. This is where Sass mixins come in.

Also Read: The Guide to CSS Flexbox

How to create Sass mixins?

Creating a mixin is very simple, all we have to do is use @mixin command followed by a space and our mixin name, then we open and close our curly brackets. Something like this.

The syntax is straight-forward:

@mixin <mixin name>
{
   // write the css here
}

So as per our example our Sass code would be;

@mixin flex {
    // write the css here
    display: flex;
}

Now we can add our flex declaration and use the mixin anywhere in our code.

How to use Sass mixins?

Now that you know how to declare mixins, we can now learn how to use them in our Sass code.

To use a mixin, we simply use @include followed by the name of the mixin and a semi-colon.

Syntax:

<selector>
{
    @include <mixin-name>
    [<other rules>]
}

As per our example:

.row {
    @include flex;
}

After compiling this Sass code into CSS, our CSS file should look like this.

.row {
    display: flex;
}

Lets take one more example for border-radius. This example specifies how to use mixin in border-radius to use it repeatedly in your website.

@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
   -moz-border-radius: $radius; 
   border-radius: $radius;
}

.box { 
	@include border-radius(10px); 
} 

Here, we use the mixin directive and give it a name border-radius. A variable $radius is used inside the parentheses to pass a radius according to or need.

After creating the mixin we can use it as a CSS declaration. As it mentioned previously it starts with @include followed by the name of the mixin.

The mixin in the above example is defined in the same file where it’s used, but you can define mixins in a partial. Just @import the file itself before you use the @include directive.

The generated CSS will look like this:

.box { 
  -webkit-border-radius: 10px;  
  -moz-border-radius: 10px;
  border-radius: 10px;  
}  

A Sass mixin isn’t restricted to just defining property rules; it can also include selectors, including parent selectors. Using this technique, you could, for example, define all the rules for a button-like link in a single mixin:

@mixin a-button {
   a {
      background-color: blue;
      color: white;
      border-radius: 3px;
      margin: 2px;
      
      &:hover {
         color: red;
      }

      &:visited {
         color: green;
      }
   }
}

Use the @include directive to include this mixin in a style, as shown below:

@include a-button.scss //assuming a-button.scss is the name of above mixin file

.menu-button {
   @include a-button;
}

and the output would be:

.menu-button a {
   background-color: blue;
   color: white;
   border-radius: 3px;
   margin: 2px;
}
.menu-button a:hover {
   color: red;
}
.menu-button a:visited {
   color: green;
}

SASS mixins with arguments

Mixins can also take in arguments to make the output more dynamic, which are passed when mixin is included and are available as variable within the mixin.

âť“ What is an argument?

An argument is a way for you to provide more information to a function. Arguments are variables used only in that specific function.

You specify the value of an argument when you call the function and these function arguments allow your programs to utilize more information.

Mixins accept arguments. This way you can pass variables to a mixin.

Here is how to define a mixin with arguments:

/* Define mixin with two arguments */
@mixin bordered($color, $width) {
  border: $width solid $color;
}

.myArticle {
  @include bordered(blue, 1px);  // Call mixin with two values
}

.myNotes {
  @include bordered(red, 2px); // Call mixin with two values
}

Notice that the arguments are set as variables and then used as the values (color and width) of the border property.

Kindly note that, you can add an infinite number of values inside of ( ) separated with ,.

In Sass mixins, – (hyphen) and _ (underscore) are treated as same.

After compilation, the CSS will look like this:

.myArticle {
  border: 1px solid blue;
}

.myNotes {
  border: 2px solid red;
}

Sass mixins – default value for arguments

We can provide default values to the arguments while defining a mixin so that even if the user doesn’t provide a value for the argument, the default values are used.

Let’s see this example:

@mixin textstyle($color, $size:12px) {
color: $color;
font-size: $size;
font-weight: 400;
}

.left-sidebar {
@include textstyle(#999999, 16px);
 }

.right-sidebar {
@include textstyle(blue);
}

The above Sass code will be compiled into the following CSS code:

.left-sidebar {
color: #999999;
font-size: 16px;
font-weight: 400
}

.right-sidebar {
color: blue;
font-size: 12px; /*default value*/
font-weight: 400  
}

As you can see in the above CSS code, in the CSS class .right-sidebar, the font-size property has taken the default value(12px) which we provided while defining the mixin.

âť— Important

Default arguments can be variables, keywords etc.

Sass Mixin – Keyword arguments

While calling Sass mixin, we generally provide the arguments in the same order in which they were declared when mixin is defined. But we can also pass the argument values by name while calling the mixin.

Let’s take a simple example and see this in action.

@mixin textstyle($color, $size : 12px) {
  color: $color;
  font-size: $size;
  font-weight: 400;
}

// calling mixin by providing argument with name
.left-sidebar {
  @include textstyle(#999999, $size : 16px)
    }

The above Sass code will be compiled into the following CSS code:

.left-sidebar {
color: #999999;
font-size: 16px;
font-weight: 400
}

It will be compiled into CSS just like the previous example. The only difference here is that while calling the mixin, we have provided the value for the argument along with the name, this makes the code more readable.

âť— Important

The name should be the same as defined in the mixin definition. So be careful, while updating the mixin, if you change the name of the argument, it may break your code.

Sass Mixin – Arbitrary arguments

SASS mixin also supports arbitrary arguments which means a mixin can take any number of arguments when its called.

If the last argument in a mixin declaration ends in …(three dots), then all the extra arguments passed when the mixin is called are passed in the last argument as a list.

Let’s take an example to understand this.

Some CSS properties can take different numbers of variables. An example is the margin property, which can take from 1 to 4 values. Sass supports this using arbitrary arguments, which are declared with an ellipsis after their names:

@mixin margin-mix($margin...) {
   margin: $margin;
}

Given this mixin definition, any of the following @include directives will transpile without error:

.narrow-border {
   @include margin-mix(1px);
}

.top-bottom-border {
  @include margin-mix(3px 2px);
}

.varied-border {
   @include margin-mix(1px 3px 6px 10px);
}

and with the expected results:

.narrow-border {
  margin: 1px; 
}

.top-bottom-border {
  margin: 3px 2px;
}

.varied-border {
  margin: 1px 3px 6px 10px; 
}

Passing Content to mixins

Most often you will use mixins for standard bits of styling that you will use in multiple places and expand with additional rules when you include them.

But you can build mixins that work the other way by passing a block of rules to the mixin. You don’t need a variable to do this; the content you pass will be available to the mixin via the @content directive.

We can pass a block to mixins with the use of @content.

Let’s say that you want to define various types of buttons. The base class may look like that:

@mixin button {
    display: block;
    font-size: 20px;
    text-decoration: none;
}

The regular button just includes the mixin, but for example the delete button needs a red colored text. So, we should change the definition a bit and write:

@mixin button($color: #000) {
    display: block;
    font-size: 20px;
    text-decoration: none;
    color: $color;
}
.alert {
    @include button(#F00);
}

By doing this we are able to pass the color and basically create another type of button. So far so good, but the cancel type of button may need gray border and we need to add a new parameter.

@mixin button($color: #000, $border: none) {
    display: block;
    font-size: 20px;
    text-decoration: none;
    color: $color;
    border: $border;
}
.alert {
    @include button(#F00);
}
.cancel {
    @include button(#000, solid 1px #999);
}

We hope you already saw the problem. We can’t continue adding more and more arguments to our base class, because it is not very efficient.

There is also code duplication at the end. That’s the perfect place for the @content directive. We are able to remove the parameters and use the mixin like that:

@mixin button() {
    display: block;
    font-size: 20px;
    text-decoration: none;
    @content;
}

.alert {
    @include button {
        color: #F00;
    }
}
.cancel {
    @include button {
        border: solid 1px #999;
    }   
}

The result is:

.alert {
    display: block;
    font-size: 20px;
    text-decoration: none;
    color: #F00;
}
.cancel {
    display: block;
    font-size: 20px;
    text-decoration: none;
    border: solid 1px #999;
}

Passing content into a mixin isn’t something you will need to do very often, but it can be useful, particularly when you are dealing with media queries or browser-specific property names.

Conclusion

To put it very simply, a mixin is a function that can output code rather than return a result.

While a function is a good way to abstract a repeated operation based on parameters, a mixin is a terrific way to abstract repeated style patterns—all with the ability to adapt the output based on parameters.

Mixins are obviously very useful and speed up your workflow, and there is a lot we can do with them.

Here are few examples of popular open source mixins.

  • Andy.scss is a collection of Sass mixins
  • SASS-MQ a Sass Mixin for handling media queries
  • Bourbon a collection of CSS mixins

So in this tutorial, we learned all about SASS mixins and how to call them in our CSS wherever we want. Using Sass mixins helps us keep our CSS code clean and write reusable styling rules.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.