Christian Juth

Sass Mixin to Prefix Properties

Published: 12/15/2016 - Edited: 12/24/2016

Prefixes are annoying, and - I think - a waste of space. I have experimented with a few different mixins to deal with this space hogging annoyance, but this one from CSS-Tricks is the cleanest example I have seen thus far.

Before

#some-div {
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  -o-box-shadow: none;
  -ms-box-shadow: none;
  box-shadow: none;
}

After

#some-div{
  @include prefix(box-shadow, none, webkit moz o ms);
}

I took this example from this website based on code from CSS-Tricks. The result may seem small, but in this project, I used the same drop shadow at least a dozen times. Each time the mixin is used I save four lines of code, so the lines saved is exponential.

The Mixin

/// Mixin to prefix a property
/// @author Hugo Giraudel
/// @param {String} $property - Property name
/// @param {*} $value - Property value
/// @param {List} $prefixes (()) - List of prefixes to print
@mixin prefix($property, $value, $prefixes: ()) {
  @each $prefix in $prefixes {
    #{'-' + $prefix + '-' + $property}: $value;
  }

  // Output standard non-prefixed declaration
  #{$property}: $value;
}

Advanced Usage

If you want to save even more lines of code, keep your browser prefixes in a '$prefix' variable. The less you have to repeat code, the more space you can save and easier it will be to make changes globally.

$prefixes:  webkit moz o ms;

#some-div{
  @include prefix(box-shadow, none, $prefixes);
}

Source CSS-Tricks.