Skip to main content

Introduction to Sass Mixin

Sass @mixin

Sass @mixin is a directive that allows you to define a group of CSS declarations that can be reused throughout your stylesheets. Mixins can be thought of as functions in Sass that take arguments and return a block of CSS code.

To define a mixin in Sass, you can use the @mixin keyword followed by a name for the mixin and any arguments you want to pass to it.

As an example:

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

In thise example:

  • This defines a mixin called border-radius that takes one argument ($radius) and applies the border-radius, -webkit-border-radius, and -moz-border-radius properties with the specified value.

To use a mixin in your stylesheet, you can include it in your CSS rules using the @include directive followed by the name of the mixin and any arguments you want to pass to it.

As an example:

.box {
@include border-radius(10px);
background-color: #ccc;
}

In this example:

  • This will apply the border-radius properties defined in the border-radius mixin to the .box class, with a radius of 10 pixels.

Default Values for a Mixin

Mixins can also include default values for their arguments, making them more flexible and easier to use.

As an example:

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

In this example:

  • The border-radius mixin takes one argument ($radius) with a default value of 5 pixels.
  • This means that if you call the mixin without passing any arguments, it will use the default value.

Using a Mixin For Vendor Prefixes

Vendor prefixes are a common challenge in writing CSS that works across multiple browsers. In Sass, you can use a mixin to generate vendor prefixes automatically, which can save you a lot of time and effort.

To create a mixin that generates vendor prefixes, you can use the @mixin directive and include the vendor-prefixed properties within it.

As an example:

@mixin transform($value) {
-webkit-transform: $value;
-moz-transform: $value;
-ms-transform: $value;
-o-transform: $value;
transform: $value;
}

In this example:

  • The $value argument is used to set the value of the transform property, and vendor prefixes are included for all major browsers.

To use this mixin in your styles, you can call it with the desired value.

As an example:

.box {
@include transform(rotate(45deg));
}

This will generate the following CSS :

.box {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
}
tip

By using a mixin to generate vendor prefixes, you can avoid repeating the same code over and over again, which can help make your stylesheets more maintainable and easier to read.