Sass Mixin and Sass Placeholder Tutorial

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Sass is a CSS pre-processor that generates CSS.  In this tutorial, we will learn about Sass mixin.   Consider this mixin that I typed into SassMeister.com

sass mixin

sass mixin

The Sass is on the left panel and the generated CSS is on the right panel.

A few things to note.  The block starting with @mixin is the mixin.  I gave this mixin an arbitary name of “box-shadow”.  The mixin takes two parameters: $blur and $spread for making box shadows.   Note that parameters are denoted by a $ in front (both in the mixin declaration and in the mixin body.)

The mixin doesn’t generate any CSS by itself unless you use @include to call the mixin.

We use @include twice to call the mixin.  Once in the style rule .my_big_box (with bigger values of $blur and $spread) and another time in the style rule .my_small_box (with smaller values of $blur and $spread).

 

See that in the generated CSS, every time you make a call of @include, the code of the mixin is output.  So if you call the mixin 10 times, you get 10 blocks of similar code, which is fine if your mixin takes parameters and you need styles of different value parameters.

Mixin with Optional Parameter

You can have a mixin with optional parameters by supplying a default value.  Do this with the colon and value in the mixin declaration as in …

sass mixin with optional parameter

sass mixin with optional parameter

Mixin with No Parameter (use placeholder instead)

But if you create a mixin with no parameters such as …

mixin with no parameter

mixin with no parameter

You get a bit of inefficient code duplication in the generated CSS.

Sass Placeholder

You would be better off using a Sass placeholder like this …

sass placeholder

sass placeholder

See how it eliminates the duplicate code in the output CSS.   Sass placeholder definition just start with a % and that’s it.  No parameters, no parenthesis, and no keyword such as “placeholder”.   To use (or call) the placeholder you use the @extend

Difference between Sass mixin and Sass Placeholder

You @include a mixin, but you @extend a placeholder.  A mixin has parenthesis.  A placeholder does not.  If you need parameters, use a mixin.  If you don’t, use a placeholder.


Tags

Share This