Stop writing vendor prefixes, autoprefixer does that for you

Anybody who writes css for the modern web has probably touched vendor prefixes at some point in time. These prefixes are required to get the most out of browsers that are supporting bleeding edge properties in ways that aren't yet part of the css3 spec. When you’re writing these vendor prefixes it’s easy to forget one or two, or maybe you add one that isn't actually required for the browsers that you’re supporting. Of course you can always check out caniuse.com to check the prefixes you need for your use case but that’s something you don’t want to do on a daily basis.

And even if you knew all the prefixes you probably wouldn't know the syntax for each property. For example, take flexbox. Flexbox uses several implementations across several browsers and writing a full stack of vendor prefixes for it would look a little bit like this:

.flexbox {
    display: -webkit-box;
    display: -webkit-flex; /* two webkit versions!?!?!? */
    display: -ms-flexbox;
    display: flex; 
}
 
.flexbox .flexitem {
    -webkit-flex-shrink: 0;
    -ms-flex-negative: 0;
    flex-shrink: 0; 
}

Using autoprofixer you can just write this and it will output the above prefixes for you:

.flexbox {
    display: flex;
}
 
.flexbox .flexitem {
    flex-shrink: 0;
}

Much better, right?

How does it work?

Autoprefixer uses caniuse.com to figure out what prefixes it should use. When you use autoprefixer you can always define what browser you want to support. You can define the browsers in a very natural way, for example you could pass it > 5%  which tells it to only support browsers that have more than 5% share in the market.

It then scans your entire css for properties that require prefixes and it automatically adds them to your css. Simple enough, right?

Setting this up for yourself

I will use Gulp to set up autoprefixer. If you’re unfamiliar with Gulp, I’ve written a post on getting started with it. I recommend you read that before you continue. If you’ve used Gulp before, grab your gulpfile and open a terminal window.

First of all we should install the gulp-autoprefixer plugin. Do this by typing npm install —save-dev gulp-autoprefixer . If you get permission errors you might have to run this command as sudo (sudo npm install —save-dev gulp-autoprefixer). Now that we have that set up we can add gulp-autoprefixer to our css task like this:

var gulp = require(‘gulp’);
var sass = require(‘gulp-sass’);
var autoprefixer = require(‘gulp-autoprefixer’);
 
gulp.task('css', function(){
    gulp.src('src/sass/**/*.scss')
        .pipe(sass())
        // the important lines
        .pipe(autoprefixer({
            browsers: '> 5%'
        })) 
        .pipe(gulp.dest('contents/css/'));
});

If you already use gulp only lines 9-11 will be important to you. What’s going on here is just a regular css compile task. We take all our .scss files and stream them to the sass plugin so they will be compiled. After doing that we stream the compiled css to the autoprefixer which will add all the vendor prefixes we need. Then the output gets saved and you’re done, you can write prefix-free css now!

A note about the above code

After publishing this I received a note from Andrey Sitnik, the author of Autoprefixer, saying that gulp-postcss should be used over gulp-autoprefixer. Below is an example of using autoprefixer with gulp-postcss. To use this you should first install both packages: npm install --save-dev gulp-postcss autoprefixer-core .

Example code:

var gulp = require(‘gulp’);
var sass = require(‘gulp-sass’);
var autoprefixer = require('autoprefixer-core'
var postcss = require(‘gulp-postcss’);
 
gulp.task('css', function(){
    gulp.src('src/sass/**/*.scss')
        .pipe(sass())
        // the important lines
        .pipe(postcss([
            autoprefixer({
                browsers: '> 5%'
            })
        ])) 
        .pipe(gulp.dest('contents/css/'));
});

The nice thing about using postcss is that you can combine multiple postprocessors. That makes it more powerful that just using gulp-autoprefixer.

How about Bourbon?

Bourbon is a sass mixing library that has many features, one of which is prefixing css. It does this by providing mixins to you that will prefix the css you pass it. An example:

a {
    @include transition(color, 200ms);
 
    &:hover {
        color: blue;
    }
}

When you compile your sass this will output properly prefixed css. The big plus for this is that you have one plugin less in your gulp file because sass (with some help of bourbon) is now prefixing your css. However, you still have to remember what properties use prefixes. That in itself isn’t bad, it’s good to know what you’re working with but it’s also easy to forget to use the mixin and end up with forgotten prefixes.

Wrapping up

In this post I've explained to you, briefly, why you shouldn't be writing your own vendor prefixes. It's easy to forget some and they're high maintenance. I also explained to you that a gulp plugin called gulp-autoprefixer can make your live a lot easier by automagically prefixing css rules that require a vendor prefix.

I also showed you really quick that you can use Bourbon to achieve effectively the same thing but it's a little bit more high maintenance than using autoprefixer.

The main point is, you don't have to write prefixes yourself. There are two very nice tools out there and each has it's own pro's and con's. I personally prefer autoprefixer because it uses caniuse.com to figure out what it should prefix and I can have 0 worries about remembering what properties need prefixing.

Getting started with Gulp

Let's talk about tools first

Lately I've noticed that many Front-end developers get caught up in tools. Should they use Less, or Sass? Do they code in Sublime or Atom? Or should they pick up Coda 2? What frameworks should they learn? Is Angular worth their time? Or maybe they should go all out on Ember or Backbone.

And then any developer will reach that point where they want to actually compile their css, concatenate their javascript and minify them all. So then there is the question, what do I use for that? Well, there's many options for that as well! Some prefer Grunt, others pick Gulp and some others turn to Codekit for this. Personally I got started with Codekit and swapped that out for Gulp later on. The reason I chose Gulp over Grunt? I liked the syntax better and people said it was exponentially faster than Grunt.

What is Gulp

After dropping all these tools in the previous paragraphs you might be confused. This article will focus on getting you started with Gulp. But what is Gulp exactly?

Gulp is a task runner, it's purpose is to perform repetitive tasks for you. When you are developing a website some things you might want to automate are:

  • Compiling css
  • Concatenate javascript files into a single file
  • Refresh your browser
  • Minify your css and javascript files

This would be a very basic setup. Some more advanced task include:

  • Running jshint
  • Generating an icon font
  • Using a cachebuster
  • Generating spritesheets

And many, many more. The way Gulp does all these things is through plugins. This makes Gulp a very small and lightweight utility that can be expanded with plugins so it does whatever you want. At this time there's about 1200 plugins available for gulp.

When should I learn Gulp

You should learn Gulp whenever you feel like you are ready for it. When you're starting out as a front-end developer you will have to learn so many things at once I don't think there's much use in immediately jumping in to use Sass, Gulp and all the other great tools that are available. If you feel like you want to learn Sass (or Less) as soon as you start learning css you don't have to learn Gulp as well. You could manually compile your css files as you go. Or you could use a graphical tool like Codekit for the time being. Like I said, there's no need to rush in and confuse yourself.

What about Grunt?

For those who payed attention, I mentioned Grunt at the start of this article. I don't use Grunt for a very simple reason, I don't like the syntax. And also, Gulp is supposed to be faster so that's nice. I feel like it's important to mention this because if you choose to use a tool like Gulp or Grunt you have to feel comfortable. A tool should help you get your job done better; using a tool shouldn't be a goal in itself.

That said, Grunt fulfills the same purpose as Gulp, which is running automated tasks. The way they do it is completely different though. Grunt uses a configuration file for it's tasks and then it runs all of the tasks in sequence. So it might take a Sass file and turn it into compiled css. After that it takes a css file and minifies it. Gulp uses javascript and streams. This means that you would take a Sass file and Gulp turns it into a so called stream. This stream then gets passed on an plugins modify it. You could compare this with an assembly line, you have some input, it get's modified n times and then at the end you get the output. In Gulp's case the output is a compiled and minified css file. Now, let's dive in and create our first gulpfile.js!

Creating a gulpfile

The gulpfile is your main file for running and using gulp. Let's create your first Gulp task!

Installing gulp

I'm going to assume you've already installed node and npm on your machine. If not go to the node.js website and follow the instructions over there. When you're done you can come back here to follow along.

To use gulp you need to install it on your machine globally and locally. Let's do the global install first:

npm install -g gulp

If this doesn't work at once you might have to use the sudo prefix to execute this command.

When this is done, you have successfully installed Gulp on your machine! Now let's do something with it.

Setting up a project

In this example we are going to use gulp for compiling sass to css. Create the following folders/files:

my_first_gulp/
    sass/
        style.scss
    css/
    gulpfile.js

In your style.scss files you could write the following contents:

$background-color: #b4da55

body {
    background-color: $background-color;
}

Allright, we have our setup complete. Let's set up Gulp for our project.

Setting up Gulp

Let's start by locally installing gulp for our project:

npm install gulp

If you're more familiar with npm and the package.json file that you can add to your project you'll want to run the command with --save-dev appended to it. That will add gulp as a dependency for your project. This also applies to any plugins you install.

Next up, we install the sass compiler:

npm install gulp-sass

We're all set to actually build our gulpfile now. Add the following code in there:

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('css', function(){
    gulp.src('sass/style.scss')
        .pipe(sass())
        .pipe(gulp.dest('css/'));
});

gulp.task('watch', function(){
    gulp.watch('sass/**/*.scss', ['css']);
});

In this file we import gulp and the gulp sass module. Then we define a task, we call the task css. Inside of this task we take our style.scss file and pipe it through to the sass plugin. What happens here is that the sass plugin modifies the stream that was created when we loaded sass/style.scss. When the sass plugin is done it sends the stream on to the next pipe call. This time we call gulp.dest to save the output of our stream to the css folder.

Think of this process as an assembly line for your files. You put the raw file in on one end, apply some plugins to it in order to build your final file and then at the end you save your output to a file.

The second task we define is called watch. This is the task we're going to start from the command line in a bit. What happens in this task is that we tell gulp to watch everything we have in our sass folder, as long as it ends in .scss. When something changes, Gulp will start the css task.

Go back to your command line and type:

gulp watch

Now go to your style.scss file, change something and save it (or just save it). You should see something happening in the command line now.

[20:54:17] Starting 'css'...
[20:54:17] Finished 'css' after 3.63 ms

That's the output I get. If you check the css folder, there should be a css file in there. You just generated that file! That's all there is to it.

Moving forward

Now that you've learned to compile sass files into css files with gulp you can start doing more advanced things. Gulps powerful syntax shouldn't make it too hard to expand on this example. Usually you just add an extra pipe to your file, call the plugin you want, repeat that a few times and then eventually you save the output file.

I hope this guide to getting started with gulp is helpful to you. If you have notes for me, questions or just want to chat you can send me a tweet @donnywals