EmilianoDecember 14, 2020

Save Time Using Mixins - Sass

What is Sass?

Sass is a CSS preprocessor that lets you write your style sheets in a more efficient and friendly way. Some of the advantages of Sass include using loops, conditionals, mixins, and variables.

Mixins

In Sass, a mixin is a set of style declarations that can be reused in different parts of the code. A basic mixin is defined as follows:

@mixin bg-transparatente {
  background-color: transpartent;
}

To use it, we simply call it like this:

.cuadrado { 
  @include bg-transpartente;
}

Mixins and conditionals

We have seen how to declare a basic mixin. Now we will see how to create a more efficient one using conditionals. As an example, we will create a mixin that lets us align elements inside a container to the left, center, and right.

This is one of many ways to align elements in CSS:

.contenedor {
  display:flex;    
  justify-content:center;
}

Even though these two lines of code are simple, they can be repeated many times in a project. To avoid this repetition, we can use the following mixin:

@mixin align-flex( $posicion ) {
  display: flex;
  @if $posicion == "izquierda" {
    justify-content: flex-start
  } @else if  $posicion  ==  "centro" {
    justify-content: center;
  } @else if $posicion  ==  "derecha" {
    justify-content: flex-end;
  }
}

Then, to use it in our code, we simply call it like this:

.contenedor {
  @include  align-flex(centro);  
  background-color: black; 
  width: 100px;
  height: 100px;
}

The possibilities of the tools Sass provides go far beyond what is shown in this example. I hope you are encouraged to try them if you have not done so yet.