Mixin in SCSS
CSS / HTML

What is the use of mixin in SCSS – SASS

Mixin in SCSS

Hi, are you looking for the answer of what is the use of mixin in scss? If yes then in this tutorial I will explain about mixin in SCSSSASS. Using this technique we can save a lot of time while writing CSS for our project.

Using mixin you can make groups of CSS declarations that you think you will need to reuse them in your project.

I will give you an example for better understanding. So focus on what I am trying to explain to you.

Understand mixin in SCSS

Let’s say we have to create more than 1 box with rounded corners (border-radius). So here we can use a mixin in SCSS to save time. We will write SCSS only one time like the given example and then we can use it with any other class using the @include method of SCSS. It means you don’t need to write the CSS again for border-radius.

Example 1 (SCSS):

/*Creating our mixin to add 10px border radius to any class, id or tag*/
@mixin radius10() {
   border-radius: 10px;
   -webkit-border-radius: 10px;
   -moz-border-radius: 10px;
}
/*Now using the mixin like this*/
.box1 {
   @include radius10;
   width:100px;
   height:100px;
   border: 1px solid black;
}

In the above example first, we have created a mixin with the name “radius10” (you can give it any name as you want) and then we have used it on a class “box1” using @include method.

In case you need to create more than 1 box with different sizes of rounded corners (border-radius) then you will write SCSS like this.

Example 2 (SCSS):

/*Creating our mixin to add any number of border radius to any class, id or tag*/
@mixin radius($value) {
   border-radius: $value;
   -webkit-border-radius: $value;
   -moz-border-radius: $value;
}
/*Now using the mixin like this*/
.box1 {
@include radius(10px);
   width:100px;
   height:100px;
   border: 1px solid black;
}
/*Applying border radius with different sizes*/
.box2 {
   @include radius(20px);
   width:100px;
   height:100px;
   border: 1px solid black;
}

Above SCSS will write the following CSS for you.

.box1 {
  border-radius: 10px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

/*Applying border radius with different sizes*/
.box2 {
  border-radius: 20px;
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

I hope this tutorial helped you.

Thanks for visiting ! Keep engaged for latest updates.

Author

I am a Full Stack Web Developer. I have more than 8 years of experience in the web design and development industry.

Leave a Reply

Your email address will not be published. Required fields are marked *