Sass in the Real World: book 1 of 4

Using mixins

Using the @mixin directive you can engineer smart and reusable code to be used throughout your application.

When using mixins within selectors, the placement of mixins has a direct impact on the cascade of your output CSS. The role of a mixin is to physically inject, or mix-in code, where referenced. When a mixin is randomly placed into a selector, depending on what is in the mixin, this could either accidentally over-write a preceding CSS rule or you may unknowingly write a CSS rule that is duplicated by the mixin.

Consistency plays a huge role in clean code. When mixins are always in a consistently expected location, this will help other authors be able to quickly scan and edit code.

In the following example notice how I included the mixin transition directly after declaring the selector. By doing so, we have a clear expectation as to the output CSS. After the included mixin is when I list the rules that are specific to this selector. Again, this pattern would follow suit with the nested .nested-foo selector.

.foo {
  @include transition(all, 0.6s, ease);
  background-color: orange;
  width: 50%;
  .nested-foo {
    width: 25%;
    margin: 0 auto;
  }
}

When using mixins, tt is considered best practice to only create mixins that use keyword arguments. By doing so, you aren't simply repeating code, but leveraging a pattern of attributes whose vales are being dynamically updated with each use.