Mixin to Prefix Properties

Avatar of Kitty Giraudel
Kitty Giraudel on (Updated on )

In case you’re interested in handling your own CSS vendor prefixing (rather than, say, Autoprefixer or Compass), here is a mixin to help with that. Rather than just appending every known prefix to everything, you pass it the prefixes you want to use, so you have more fine grained control over the output.

Simple version

/// Mixin to prefix a property
/// @author Kitty 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;
}

Usage:

.selector {
  @include prefix(transform, rotate(45deg), webkit ms);
}

Output:

.selector {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

Advanced version

Note that this version uses Sass maps, hence requires version 3.3 or higher.

/// Mixin to prefix several properties at once
/// @author Kitty Giraudel
/// @param {Map} $declarations - Declarations to prefix
/// @param {List} $prefixes (()) - List of prefixes to print
@mixin prefix($declarations, $prefixes: ()) {
  @each $property, $value in $declarations {
    @each $prefix in $prefixes {
      #{'-' + $prefix + '-' + $property}: $value;
    }

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

Usage:

.selector {
  @include prefix((
    column-count: 3,
    column-gap: 1.5em,
    column-rule: 2px solid hotpink
  ), webkit moz);
}

Output:

.selector {
  -webkit-column-count: 3;
  -moz-column-count: 3;
  column-count: 3;
  -webkit-column-gap: 1.5em;
  -moz-column-gap: 1.5em;
  column-gap: 1.5em;
  -webkit-column-rule: 2px solid hotpink;
  -moz-column-rule: 2px solid hotpink;
  column-rule: 2px solid hotpink;
}