How to Create and Use Mixin in the Sass?

It is very hard to write long CSS code , but Sass allows us to write smart code. Personally I like SASS because it gives me a lot of comfort while building websites, specifically mixin. Before I get started, let me show what I will cover in this article.

  • What are Mixin in the Sass?
  • How to create Mixin in the sass?
  • Passing arguments in the sass Mixin
  • How to use the Mixin in the code?

What are Mixin in the Sass?

Mixin is used in Sass, which is a CSS preprocessor. Mixin works as a function in Sass and accepts arguments. Means you can pass arguments in the mixin. It helps to reduce the repeated code.

Mixins allow us to use the reusable widget style for the web page. And avoid too many classes in the HTML document.

How to create Mixins in the Sass?

You can follow the below steps to create a mixin which is very easy.

  • Mixin starts with @ symbol
  • Write the mixin keyword after @symbol
  • After symbol and mixin, you need to give the mixin name
@mixin circle{
width :100px;
height:100px;
border-radius:100px;
}

In this example, we created a mixin with a name circle with few CSS properties.

Create a Mixin with Arguments

A mixin should accept arguments for re-usability. For example, in the above example the circle’s height and width will be always same. In case we need a larger circle or a small circle we cannot create with static CSS properties.

Passing Arguments in the Mixin

Create the same object as per the example after the name write braces and pass the arguments starting with the $sign, see the below example

@mixin circle($width, $height, $radius){
width :$width;
height:$height;
border-radius:$radius;
}

In this example we passed the arguments to define the properties values as per our requirements. For example, we need to create a circle with different sizes like width:100px, height:100px and radius: whatever.

How to use the mixin in the code?

The usage of mixin is quite easy you just need to include them in the class.

.avatar{
 @include circle(36px, 36px, 100px);
}

In the avatar class we used a circle mixin with size and radius values. So we can create any type of mixin with arguments which will make the code organized and shorter.

Conclusion

Working with sass we can write the mixin for different widgets, and provide the arguments as the CSS property value. Mixins are CSS preprocessors, which allow us to write shorter code and avoid writing the code again and again. We can create the mixin starting with @ symbol with name and braces to pass the arguments.


Related Posts

Tags: CSS, Sass,