Sass mixins replaces a portion of code in CSS

According to MDN Web Docs a mixin is a class “in which some or all of its methods and/or properties are unimplemented, requiring that another class or interface provide the missins implementations”. In other words, Sass mixins make it possible to reuse code or behaviour in different classes or objects without using inheritance. Without applying mixins, you’d have to repeat the same code quite often to some functionalities. Or, it’d be required to create a separate HTML class. Mixins resolve that problem. Why don’t we look at some examples of how mixins can be applied in Sass?

How to create a Sass mixin?

To create a mixin all you need to do is write @mixin followed by its name, brace brackets inside which you list the declarations:

In order to make the mixin work, we need to apply the key word @include with its name inside the class or the element we’d like it to be used for:

sass mixins

This is how it looks on front-end, after applying the mixins to the service info-boxes:

sass mixins

Thanks to flexbox, a Boostrap feature, each card is centered both horizontally and vertically. Despite different lengths of text inside each card body, the read-more buttons are positioned equally towards the bottom of the card bodies, after setting the margin-top “auto“. We might as well apply a mixin to do so. The code would look the following way:

sass mixins

Mixins can also take arguments. To apply the mixin, once again we write @include “name”(<arguments…>): After “$” you give the variable name.

sass mixins

Sass mixins provide a method that implement a behaviour

Sass mixins make your CSS code much better, as you do not have to refer to HTML every single time you want to apply a functionality to a given class. Mixins can be treated as functionalities. Mixins can be successfully applied in RWD, which we will touch upon next time.

The feature image: Maik Jonietz on Unsplash CC.