First things first, this mixin was written in the SCSS format. Sass format is a little different. You can check out the same mixin in Sass here.

So in a nutshell, mixins can be helpful when you have elements that have similar styling but you don't want to write similar code over and over again. For example, if you have text blocks that all have borders with slightly different values, you can make a mixin for your borders and then reference the mixin within the CSS for each text block and just put in the specific values that match the variables within the mixin.

The first step is to create the mixin structure and give it a name:

  @mixin div-styling {

  }

Then add the styling you want included:

  @mixin div-styling {
  border: ;
  letter-spacing: ;
  font-size: ;
  margin: ;
  }

Finally, you just need to add the values for the styling, and where you want to allow the elements that use the mixins to make adjustments, you replace values with variables:

  @mixin div-styling ($border-color, $spacing, $size) {
  border: 1px solid $border-color;
  letter-spacing: $spacing;
  font-size: $size;
  margin: 0;
  }

So above, any element that uses the mixin will get a 1px, solid border but will be able to choose the border color. Also, every element that uses the mixin will have all margins removed since there is no variable set for margins. Also note that the variable names are references within the "()" on the top line of the mixin and separated by commas.

And when using the mixin in your code, you can just reference the mixin name after "@include" and pop in your own variable values, separated by commas in the same order as the mixin:

  h1 {
  @include div-styling(red, 0.3em, 1.5em);
}

So an h1 will inherit the div-styling mixin values, along with a red border, letter spacing of 0.3em and a font-size of 1.5em.

Full Pen can be found here.


444 0 0