SASS Mixins

SASS mixins are portions of reusable CSS that can be used in your project without having to be repeated like when having to write normal CSS.

A common example of a mixin in use is the border-radius property. Usually in older versions of browsers such as Firefox and Chrome, you had to specify additional -moz- and -webkit- prefixes respectively in order for the property to work in those browsers.

The CSS for this might have looked like this:

.border {
  -webkit-border-radius: 5px; 
  -moz-border-radius: 5px; 
  border-radius: 5px;
}

To define a mixin, use the @mixin syntax followed by the CSS property. You can also pass in values to make your mixin flexible.

A border-radius mixin might look like the below.

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

You can include the mixin using @include.

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

Mixins do not have to be browser-specific CSS properties. You can create mixins to handle common CSS features that are likely to be re-used throughout your project.

For example, let’s assume that the links on your website share similar behaviour when they are clicked on, hovered over etc. A mixin that sets the link colours could be defined.

@mixin link-colours ($linkColour, $visitColour, $hoverColour, $activeColour) {
  a {
    color: $linkColour;
    &:visited {
      color: $visitColour;
    }
    &:hover {
      color: $hoverColour;   
    }
    &:active {
      color: $activeColour;
    }
  }
}

@include link-colours(blue, black, green, red);

Note that the & character refers to the parent element (a).

Default Values

The parameters passed into the mixin can also have default values. This is specified using the $param: value syntax, where $param is the initial parameter passed into the mixin, and ‘value’ is the default value to give to that parameter.

@mixin font($size, $color: black) {
  font-size: $size;
  color: $color;
}

h1 {
  @include font(12px);
}

As the @include only passed in one parameter, the default colour for the h1 property would be black.

In conclusion SASS mixins are a powerful feature enabling you to write less CSS and speed up your workflow.