Automatically add vendor prefixes to properties and values in Sass

in code


I came up with this myself and discovered after that other developers came to exactly the same solution for the problem of vendor prefixes. CSS3’s flexbox is the newest greatest thing in my life. It makes incredible sense and lets me do things like:

  1. Vertically center child elements and other content without having to use hacks like one-line-of-content-with-a-huge-line-height or absolute positioning coupled with matrix transforms.
  2. Dynamically add columns to a container without having to individually resize each column.
  3. No more fucking floats.
  4. Evenly space content, period.

It’s great, and support for it is still incomplete. When I worked on the new Ouro site last week I ran into the problem that content collapsed or looked strange on Eadaoin’s borrowed (thank you!) iPhone and iPad. In mobile Safari, even on iOS 8, flex-related properties and some rules* still require vendor prefixes, so I wrote a pair of Sass mixins to add those prefixes for me:

@mixin prefix($property, $value) {
    // Automatically add vendor prefixes to a CSS property.
    // Mozilla Firefox.
    -moz-#{$property}: $value;
    // Microsoft Internet Explorer.
    -ms-#{$property}: $value;
    // Webkit Browsers (Chrome, Safari);
    -webkit-#{$property}: $value;
    #{$property}: $value;
}
@mixin prefix_value($property, $value) {
    // Automatically add vendor prefixes to a CSS value.
    // Mozilla Firefox.
    #{$property}: -moz-#{$value};
    // Microsoft Internet Explorer.
    #{$property}: -ms-#{$value};
    // Webkit Browsers (Chrome, Safari);
    #{$property}: -webkit-#{$value};
    #{$property}: $value;
}

The output CSS can be a bit messy, and so if performance of your CSS is a concern then you will need to add browser detection and then write a separate set of rules for mobile Safari.

* This was a strange one, but apparently other such cases exist. Where with other rules I had to prefix the property (before the colon), with display: flex I had to prefix the value, after the colon, to be display: -webkit-flex;.



March 20

in me


Your email address will not be published. Required fields are marked *