How to choose between rem and em

A few days ago I found this article that argues for using rem units when defining font sizes. Generally speaking this is good advice. The rem comes with great predictable behavior, just like pixels do. But the rem also comes with accessibility advantages. When a user changes the font size in their browser settings, the rem and em unit will both respect that and resize accordingly while the pixel unit doesn't. That's great news for the user. But how do you choose between rem or em? Time to go in depth on what these units do. First I'll explain how each unit works and what they do. Based on that I'll explain how you can make the decision for a sizing unit.

The rem unit

Since the rem unit is the easiest one to understand and use, it will be the sizing unit I start off with. The rem is relatively new but if you don't have to support IE8 anymore you can safely use it. Rem is short for "root em", that's because it is a lot like the em unit except it is relative to the root font size.

So, what does this all mean? The rem unit is a sizing unit that's related to font size. With default browser settings 1 rem should be equal to 16px. That is because the default browser font size is, you may have guessed it, 16px. So using rems is almost as easy as using pixels. Want to make something 80px wide? That will be 5 rem please.

More complicated things like 100px will require you to do some math but if you use something like Sass I recommend that you check out Bourbon.io, it provides a rem-calc function to help you calculate rems.

A workaround many people use is to set the body's main font-size to 10px so 1 rem equals 10px on their website instead of 16px which will make working with rems a lot easier. The cool thing about the rem unit is the fact that 1 rem will always be the same size everywhere on the page, no matter what.

The em unit

The em unit is a lot like the rem unit. The difference between them is that the rem unit is always relative the the root font size. The em unit is relative to it's containing element. An h1 that is directly inside of the body and has a font size of 2 em will have a font size of 32px if we assume the default browser font size is in tact. If you would add a link inside of that h1 and you would want that to be 24px you first instinct would probably be to use 1.5 em as a font-size for that anchor tag. Let's try this out.

So... what went wrong here? The header has a 2 em font size, the anchor is 1.5 em so the anchor should be smaller that the rest of the text, right? Except, the anchor is larger than the rest of the header text which makes no sense. Remember that I stated earlier that the em unit is relative to it's containing element? That's why the anchor is larger than the header text. The anchor is a child of the header so a 1.5 em font-size means that the anchor's font size should be 1.5 times the size of the anchor text.

This is something that makes the em a complicated unit to work with, you can imagine that deep nesting with multiple font sizes can get really ugly at some point. A simple demonstration:

What you see here is a list with a nested list. The outer list has a larger font size than the inner list. This happened because I set a 0.8 em font size on the ul tag. So when there's a nested list, this 0.8 em is relative to the 0.8 em font size the outer list already has. So the outer list is 80% the font size of the body. The nested list is 80% the font size of the outer list. Confused? I understand, the em isn't a very straightforward unit.

Making the decision

Now that we know how both units work we should be able to make an informed decision. So, should we use rem or do we use em for our sizing? The answer, according to me, should be both. Whenever you want to have absolute control over a size you probably want to use rem. An example would be an element that you would normally make 100px wide. You want that element to have the same size, no matter where in the document you use it, the size has to be 100px. That is a case where you should convert that 100px to rems.

However, there are cases like the link inside of an header element where you might not want to set an absolute size. You might want to say this header element should have a font size that is two times larger than the body text that it's above. That would mean that you want to use a 2 em font size because then you know that your header is always two times larger than the body text of the element. Taking this one step further you might want to say that the anchor tag's font size should be 75% percent of the header's font size. That's 0.75 em.

What I would like to conclude here is that both of these sizing units are extremely powerful. One is very good for setting absolute sizes that are still accessible and adaptable. The other is good for setting relative sizes, whenever something should be x times the size of something else, regardless how big, the em unit is your friend. I do think, however that the rem units should be the unit of choice in many situations. But especially with margins, paddings and certain spacing situations I have found the em unit to be the best choice because all those sizes are usually relative to another size and that's where the em shines bright.

So, next time you're faced with the rem vs. em decision I hope you think about the way they each work and make an informed decision. My rule of thumb is: rem replaces absolute pixel sizes, em is for relative sizes. If you have questions for me, feedback or want to get in touch you can always contact me on Twitter.

Consistency and discipline over motivation

One of the beautiful things about being a developer is that many of us actually have the opportunity to take an activity we enjoy, and make it our job. Many developers are happy to do some extra work or learn something when they're at home or in the weekend just because they are so eager to learn and play. While this is pretty awesome, it won't last forever. You won't be motivated to learn every single day. Especially once you start doing development as a full-time job. I experience this as well, sometimes I have a couple of days or even weeks where my motivation is through the roof. I'll get tons of work done and the days just fly by. On other days I just can't seem to get started, everything is distracting and the motivation just doesn't seem to be there. When I look at some of the more senior developers I know, it seems that they have moved past this phase. They always seem to be motivated and sometimes they just seem extra motivated. They just seem to have no shortage of the good stuff! How do they do this?

Is it motivation you should look for?

If you think about it, motivation isn't worth much. It's just not there all the time and you can't build a solid career based on it. When I was looking for ways to improve motivation I came across posts like this, telling me that I should get disciplined. Some went even further and said that motivation just isn't worth your time.

Because of these posts I started to realize that motivation is a great driver of productivity. But only when it's there. When motivation isn't there, every job seems like a chore. Have to adjust a form on a website? It sounds terrible when you're not motivated. You'd have to create a new input field, maybe change a database table and more. You get tired just by thinking about it. But then consider doing that same thing when you're motivated. You probably would get excited because you get to possibly improve the product and code base that you're working on. This isn't feasible in the long run though, when you want a job in development you'll need to train yourself to become more consistent, more disciplined. Motivation will be the bonus, not the requirement.

Changing motivation into discipline

If you want to be more disciplined you'll sometimes have to be pretty tough on yourself. There's rarely a valid excuse to not do what you're supposed to do. So instead of postponing things until you feel motivated or obliged to do them, just get started. If you do this, and are consistent about it, you'll see that it helps. I often find that it helps to not jump in headfirst like you would when you're super motivated but to just sit back first. Take 15-20 minutes to figure out what it is that you're going to build, what code are you going to write. Figure out what sub tasks there are and split them up in blocks that will take about 40 minutes to complete. If you do this, you will have a great structured overview of what you're going to do. You'll know how busy you are for the day or week and you'll be able to plan accordingly. During those 40 minute work cycles try to turn off notifications that might distract you. Discipline yourself to only check notifications in between your 40 minute cycles.

After a 40 minute cycle it's time to take a quick break. And try to make it an actual break, get up and grab a drink. If there's email or anything similar that requires your attention, take a peek. Reply if needed or add replying to your to-do list. Make it a part of a 40 minute cycle if the email requires you to figure something out in-depth. Otherwise, use the break or extend the break a little (but not too much, 10 minutes should be the maximum). In the beginning you might feel like you're restricting yourself because everything has to be thought about or planned in, you can't just start doing something and then do something else until you're out of motivation. That's fine, you are training yourself to have a consistent and disciplined workflow. If you find that 40 minutes is too long or too short for you you can always change the cycles. You could even do that on a day-to-day basis if you feel like it's appropriate for the tasks you're working on. I personally found after a few weeks that I prefer 50 minute cycles with 10-15 minute breaks.

The benefits are real

When I look at more senior developers I notice that many of them have a workflow similar to this. They take multiple short breaks throughout the day and between those breaks they tend to be very focused on the tasks they have to complete. They don't have their Slack open all the time and they work on a single thing at a time. And they are consistent about that. Everyday they seem to be able to flick the switch and go into work mode. Of course they still have more and less motivated days, but a motivated day will just make them super productive instead of only productive because being productive is their default setting.

So let's get out there and become consistently more disciplined!

Using Flexbox in the real world

The Flexbox module for css was built with the intent to make a more robust, less hacky way to layout elements on pages. When you're building a webpage you often don't know how high or wide every element could or should be. This can cause problems in certain layouts which lead to ugly hacks. Flexbox solves this widespread layout issue. The module has been in development for quite some time and the W3C gave the spec a "last call working draft" status back in september of 2014. The browser support for this module is very good if you don't have to support IE9 so you can safely use it. In this post I will provide a few code examples to show you how you can use Flexbox in some everyday situations.

Creating a filmstrip

Have you ever created a horizontally scrolling filmstrip kind of module? You know the size of the each element in the strip and the size of the containing element but the size of the inner element, the filmstrip itself is unknown. This would normally result in a layout like this and you would have to use Javascript or hardcode the size of the inner element to make this work.

So what would happen if you used Flexbox for this? Well, Flexbox allows an element to grow, not only on the y axis like an element normally does, but also on the x axis. It's one of the reasons Flexbox is really cool. Let's try this.

It's pretty neat, isn't it? Between the first and second example there's only three lines of code that are different. Okay, actually there's a little more but I'm not counting in the vendor prefixes because you don't have to write those if you use an autoprefixer. The first difference is that we give overflow-x: scroll; to the filmstrip container, that's just to make the contents scroll. The second step is to set display: flex; on the inner element. If you did only these two things, the items inside of the inner element will shrink to fit inside of their container. You don't want this so the last thing you do is add flex-shrink: 0; to the filmstip items. The shrink property has a value of 0(false) or 1(true). There's also a flex-grow  property, it's the same as the shrink property but it determines whether an element will grow or not.

Vertical centering

Ever since I started writing css this has been a problem. How do you center an element, with or without a known height, in a container that is or isn't flexible? No matter how you look at it, vertical centering is annoying. I've used hacks that would absolutely position the centered element at 50% from the top and then I would use a negative top margin to push the element towards the center. Another method is to use translating which is slightly cleaner but you still have to use position absolute and a top offset of 50%. You could display your stuff as if it's a table and then vertically center content which works well but it just doesn't feel right. It starts to feel plain wrong once you've tried to do this with Flexbox.

So in this example I've set up a container and inside of that container is an image. Flexbox is used to center the image both vertically and horizontally inside of it's containing element. The property that is used for vertical centering is align-items . The property that is centering horizontally in this example is justify-content . In my opinion, this is the best way to vertically align items I've seen.

Fitting things into a container

The filmstrip example gave this one away already but Flexbox can be used to fit an unknown number of items into a container. This is really nice if you have a couple of images but you can't really be sure of how many. You could optimize for a certain number, let's say four in the case of this example. And then for the edge cases where you have five images or more, you have Flexbox to make the images smaller so everything will still fit nicely into the containing element. Let's check it out.

All we had to do to achieve this is add display: flex; to the containing element. In the first example we saw that, by default, children of an element with display: flex; will shrink to fit inside of that container.

Conclusions and further resources

In this post I showed you three examples of what you can achieve with Flexbox and how you can do that. Note that we just used Flexbox for three small things and that I didn't mention Flexbox as a method of laying out your entire page. The reason for this is that Flexbox is not intended for that. There is a spec on the way for laying out your entire page and it's called grid.

If you're looking for a good overview of how Flexbox works I recommend that you visit this cheatsheet on css-tricks.com. This cheatsheet provides a lot of information on how you can use Flexbox and what properties it has. Lastly, if you're looking for more examples of what problems you can solve with Flexbox check out this "solved by Flexbox" page.

Filling in the blanks with calc()

One of the things in css3 that I don't see used very often is the calc() function. Even though this function might not be useful in every scenario it certainly has it's own use cases. In this post I'll try to outline a few of these use cases for you. First, let's start with a quick introduction to the calc() function.

What is calc()?

Calc()  is a function that was added to css3. It allows you to perform calculations on a certain property value, for example the width, font-size or even the margins of an element can be calc()-ed. The syntax for it is quite simple:

.my-class {
    width: calc(100% - 3em);
}

This code snippet sets the width of an element to 100% minus 3em. What's interesting about this is that we're combining both percentages and em values. So you can be partially fluid and partially fixed in your layout. Calc is very powerful and will perform this calculation whenever the element is being layed-out on the screen, making it incredibly flexible. An important thing to notice here is that there are spaces around the minus operator. These spaces are required.

Using calc for gutters

When building your layout you will often want to have a certain gutter in it. For instance, you could want a gutter that is exactly .75em all the time between two elements. For these cases calc is a perfect fit. Here's an example of that.

In the embedded codepen you'll see that we used only a small amount of css to accomplish this layout. A quick look at the css:

.item {
    height: 50px; 
    float: left; 
} 

.item-1 {
    width: 25%;
    background-color: #c0ff3e; 
} 

.item-2 { 
    width: calc(75% - .75em); 
    margin-left: .75em; 
    background-color: #0ff1ce;
}

The nice part about this is that a use can adjust their font-size and the layout will adapt to that because we've used ems. The calc()  function will make sure that our page will still look pretty. If you take this approach to the next level I'm pretty sure it should be possible to use calc()  in a very advanced and flexible grid system.

Calc to fill up the page

There are times where you might want to make an element take up all the width minus some known portion of the page. This becomes interesting in the case of a sidebar with a known width and content that should make up the rest of the page. Let's jump straight in with an example, shall we?

If we ignore all the kitten cuteness that Placekitten.com is providing this example with we're left with this piece of relevant css.

.item-1 {
    width: 250px;
}

.item-2 {
    width: calc(100% - 250px - .75em);
    margin-left: .75em;
}

What this demonstrates is that it suddenly becomes easy to have a partially fixed and partially flexible layout and that calc is very powerful because you can mix all kind of values. Pixels, ems, percentages, calc()  will calculate them for you. It's pretty cool actually.

How about browser support?

I'm glad you asked, browser support is more than decent for the calc feature. All new browsers have implemented it and they have done so for quite some time. Even IE has had support for some time, they only didn't implement multiplying and dividing until IE10. For an up to date list of support you can refer to caniuse.com.

Conclusion

In this post you've learned what the calc()  function is in css3 and I've showed you two real word examples of when you might want to use calc()  in your own projects. Browser support is good so there's nothing stopping you from sprinkling some calculations in to your css. If you have questions, suggestions or feedback you can always send me a Tweet.

Death by papercut (why small optimizations matter)

It's not easy to write good code. It's also not easy to optimize code to be as fast as possible. Often times I have found myself refactoring a piece of code multiple times because I could make the code easier to read or perform faster. Sometimes I've achieved both. But when a project would grow larger and larger things would still feel a little slow after a while. For instance, changing something from doing four API calls to six wouldn't matter that much, right? I mean, each call only takes about 10ms and everything is very optimized!

This is death by papercut

In the example I mentioned above, doing two API calls, 10ms each, isn't a very big deal in itself. What is a big deal though, is the fact that we're doing four other calls as well. So that means that we went from 40ms in API calls to 60ms. that's a 50% increase. And then there's also the overhead of possibly extracting the data you want to send to the API from the DOM and also parsing the API's response on the client will take extra time. Slowly all these milliseconds add up. On their own every part of the application is pretty fast, but when put together it becomes slower and slower.

I'm not sure where I heard this first but I think it's a great one. All these not-so-slow things stacking up and then becoming slow is like dying from papercuts. Each cut on it's own isn't a big deal, but if you do enough of them it will become a big deal and eventually you die a slow and painful death. The same is true in web development, and any other development field for that matter.

So if we should avoid dying by a papercut, and papercuts on their own don't really do damage, how should we do that? Every block of code we write will cost us a very tiny bit of speed, that's inevitable. And we can't just stop writing code in order to keep everything fast, that's not an option.

Staying alive

The death by papercut scenario is a difficult one to avoid, but it's also quite simple at the same time. If you take a good hard look at the code you write you can probably identify small bits of code that execute but don't actually do much. Maybe you can optimize that? Or maybe you're doing two API calls straight after each other. One to fetch a list and a second one to fetch the first item on that list. If this is a very common pattern in your application, consider adding the first item in that initial API response. The win won't be huge, but imagine finding just 4 more of these situations. You may have just won about 50ms of loading time by just optimizing the obvious things in your API.

Recently I came across an instance in my own code where I wanted to do a status check for an X amount of items. Most of the items would keep the default status and I used an API to check all statuses. The API would check all of the items and it would return the 'new' status for each item. It was pointed out to me that the amount of data I sent to the API was more than I would strictly need to identify the items. Also, I was told that returning items that won't change is a waste of bandwidth, especially because most items wouldn't have to change their status.

This might sound like 2 very, very small changes were made:

  • Send a little less data to the API
  • Get a little less data back from the API

As small as these changes may seem, they actually are quite large. First of all, sending half of an already small request is still a 50% cut in data transfer. Also, returning less items isn't just a bandwidth win. It's also a couple less items to loop over in my javascript and a couple less DOM updates. So this case save me a bunch of papercuts that weren't really harming the project directly, but they could harm the project when it grows bigger and bigger and more of these small oversights stay inside of the application, becoming harder and harder to find.

Call it over optimizing or call it good programming

One might argue that what I just described is over optimization, which is considered bad practice because it costs quite some effort and yields only little wins. In this case, because the functionality was still being built it was easy to see one of these small optimizations. And the right time to do a small optimization is, I guess, as soon as you notice the possibility to do that optimization.

I haven't really thought of code in this mindset often, but I really feel like I should. It keeps me on top of my code and I should be able to write more optimized code right from the start. Especially when it comes to data fetching from an API or from a database, I think a very careful approach might be a good thing. Let's not send a request to the server for every little thing. And let's not run to the database for every little thing all the time, that's what caching is for. The sooner you optimize for these small things, the easier it is and the less trouble it will cause you later on.

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.

How I improved my workflow with Imagemagick

When working with assets you will often want to change some of them. My personal experience is that I often want to resize images, stitch them together, blur them or convert them from .png to .jpg. When I had to do this I usually sighed, fired up Photoshop, created a batch and then ran everything in my folder through that batch. When I realized I got it wrong I would have to do this again and Photoshop usually crashed at least once in the process as well. Needless to say, I did not enjoy adjusting my assets. Until I didn't have Photoshop anymore...

Changing workstations

In december I switched from an OS X oriented workplace to an Ubuntu oriented workspace which meant that I didn't get to have Photoshop on my machine (without jumping through hoops). This wasn't a problem because I didn't have to work with assets as much as I used to and when I did I would just ask somebody else to do the tedious tasks for me.

But then I remembered Imagemagick. In the past I've used their PHP library to resize images on my webserver, but under the hood that actually uses the Imagemagick command line tool. And since I was working with a Linux machine I figured I could install Imagemagick and use it. And so I did. And it's beautiful.

Start using Imagemagick

Before you can use Imagemagick you have to install it, go to their install page and find the appropriate version for your machine. Surprise, it turns out they have an OS X version as well. After you've installed Imagemagick you should prepare some images to resize.

Resizing images

Resizing images is surprisingly simple. Open up a command line, navigate to the folder where you have your image and type this into your command line.

convert myimage.jpg -resize 50% myimage_half_size.jpg

This will scale your image down to 50% of it's original size. If you have several images to do this with you might run something like:

for "x" in *.jpg; do convert $x -resize 50% half_size_$x; done;

Pretty simple, right? You can also scale images proportionally to a pixel value like this:

convert myimage.jpg -resize 250x myimage_250.jpg

This will make the image 250px wide and scale the height proportionally. Scaling an image based on height is similar but place the pixel value after the x:

convert myimage.jpg -resize x250 myimage_250h.jpg

Manipulating image quality

After resizing your images you might want to optimize their quality a bit as well. I usually get extremely high quality assets and they can be as large as 2-3Mb sometimes. After resizing they might already be around the 100Kb, but giving up a little quality can take them down to 60-70Kb. Here's the command to do that:

mogrify -quality 60 myimage_lq.jpg

Instead of convert I used mogrify for this snippet. Mogrify is used for in-place manipulating of images, so it overwrites your image. If you don't want this you can just substitute it with convert and use it just like you did earlier.

Wrapping it up

With the commands you've learned in this post it should be easy enough to optimize and manipulate your images in the command line. For more examples check out the usage section on the Imagemagick website. I personally feel like using Imagemagick has improved my workflow and I hope it can (and will) do the same for you.

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