Converting CSS to Sass (And Cleaning Things Up in the Process)

October 9, 2014

Filed Under: Front-End Design

Update: Tim Gummer emailed me to let me know that there are some excellent CSS to Sass converters out there online: http://css2Sass.herokuapp.com/ and http://sebastianpontow.de/css2compass/, for example. If you’re just looking to quickly convert some old CSS, that should do the trick — but you would miss out on some fun learning opportunities.

I recently had to do some substantial modifications to a site I built before I started using Sass. Opening up the the CSS file felt like I was breaking out the old abacus: How had people ever worked this way? How could you write CSS without variables? You mean you kept all the CSS in a single super-long file? When you needed to change a color you did find and replace? It was horrible.

(This project was less than two years old, by the way.)

So before I got started on the modifications, I decided to move the project into Sass. If you’re moving an old CSS project into Sass, you’re probably not going to take advantage of everything that Sass (or Compass) has to offer, but you’ll at least be able to break things into partials, use variables, and set up a few mixins. I.e., your work environment won’t be miserable.  Below is the process I followed, which should serve more as a loose guide than set in stone rules.

Step 1: Get Set Up with a Sass Compiler

I use Grunt for this sort of thing. You could use CodeKit or Gulp, but these instructions are for Grunt, because Grunt is great. If you’re scared of Grunt, don’t be. Just follow the instructions. You don’t have to know what any of this means for it to work — it’ll just seem magical and mysterious, which isn’t a bad way to live.

To install Grunt, you first have to install node.js. Go to their website and click the big green Install button. Then: open up your handy text editor and paste this text in there:

{
"name": "Cool Rad Project",
"version": "2.0",
"devDependencies": {
"grunt": "~0.4.1"
}
}

Save that file as “package.json” wherever you’re going to be working on this. If you’re using WordPress locally, you can put this in your theme’s root folder.

The next step is the only remotely scary step here. You ready? Okay: open up your terminal (on a Mac, you can just type Terminal into your search bar) and type the text “CD “. Make sure you have that space in there. Then click on the folder you saved your package.json to, and drag it into the terminal window. Hit enter. All you’re doing here is Changing Directory (that’s what the CD means). Then, just type this: “npm install”. That’ll do some stuff. Once it’s done, type “npm install -g grunt-cli”. There! Now you have Grunt installed.

To actually do anything with Grunt, though, you’ll need to do a few more things. In your terminal window, type the following:
npm install grunt-contrib-Sass --save-dev
That’s just installing the Sass plugin for Grunt. Once you have that in there, open up your handy text editor and paste the following text:

module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// this is where you set up your Sass settings. Once you know what you're doing, you can change thse.
Sass: {
dist: {
options: {
style: 'compressed'
},
files: {
'style.css': 'Sass/style.scss'
}
}
}
});
// this is where you say, hey, I'm using that Sass thing that I just created settings for.
grunt.loadNpmTasks('grunt-contrib-Sass');
// this is where you have Grunt compile your Sass when you type "grunt" into the terminal
grunt.registerTask('default', ['Sass']);
};

Save this file as “gruntfile.js” in the same directory as your package.json.

Okay! Now you have Grunt all ready to compile your Sass. But you don’t have any Sass yet, so Grunt doesn’t have anything to compile. If you type “grunt” into the terminal, you’ll get an error message (but you can try it anyway if you want. It won’t hurt anything.)

Step 2: Set Up Your Basic Sass Files

First, in the same directory you put your gruntfile.js and package.json, create a folder called “Sass.”

Then open up your old clunky CSS file — the one you want to convert to Sass — and save it in that Sass folder with the name “style.scss”. You can close your CSS file. You’re done with that crap now.

Go back to that terminal window you left open, type “grunt” and hit enter. You should get a message (among others) that a file called “style.css” was created. Congratulations! You’re now using Sass. Go update your LinkedIn. Revise your resume. Demand a raise.

Step 3: Set Up Your Partials

Okay, so you’re technically using Sass now, but you’re not actually doing anything with it. Right now you just have slightly more inconvenient CSS. Let’s turn it into some slightly more convenient Sass.

One of the beautiful things about Sass is the ability to create partials. What this means is that you can divide your CSS into as many files as you need to make it manageable, and Sass compiles all of those into one big CSS file, which is what you use on your site. So your site visitors don’t have to download thirty tiny CSS files, and you never even have to look at that big messy CSS file. It works great for everyone.

To get going on this life-changing magic, create a folder in that Sass folder called “partials.” Copy and paste your “style.scss” file into the partials folder. Rename it “_shame.scss”. Go back to your original “style.scss” file, open it, and delete everything. Yes, delete it all. It feels great, doesn’t it? Now, instead, type a single line:

@import "partials/shame";

Go back to the command line and type “grunt” again. If you don’t get an error message, congrats! You just made your CSS even more inconvenient.

Now for the actual convenient part. Go through and find a section of your CSS that you want to break into a smaller file. If you already have your CSS divided into sections or organized in some way, this should be pretty easy. Let’s start with your footer. Find all the CSS that is particular to just your footer, cut it (i.e., command + x), and paste it into a new text-editor document. Save that document in your Sass > partials folder with the name “_footer.scss.”

Now: in your style.scss file, add another line under the first one, so that it looks like this:

@import "partials/shame";
@import "partials/footer";

Go through this same process for every part of your CSS. This will take some time — how much time depends on how organized your original CSS was. You want to end up with all the parts of your CSS separated into their individual files with corresponding @import statements in your style.scss file.

You may end up with some unidentifiable junk in your _shame.scss file. You’ll want to either figure out what it does and put it in the appropriate partial file (and maybe think about renaming your classes to something easier to understand) or, if it’s not doing anything, delete it. Once your _shame.scss file is empty, delete it, and delete the corresponding @import statement in your style.scss file.

Make sure that everything is saved, and go back to your new friend at the command line and type “grunt”. It should compile all your new partial files into a single compressed CSS file. If you get an error message, you probably have an @import statement for a file that doesn’t exist; check your spelling. If you don’t get an error message but some of your CSS styles appear to be missing, you probably forgot an @import statement for one of your partials.

Once you know what you’re doing, you can organize your partials however you want.  I often will have subfolders in my partials folder: the header usually gets its own folder with all the elements broken into separate partials, and likewise with the homepage any anything else that’s big enough to merit separate files. That’s one of the great things about Sass — you can customize it however makes sense to you or your team.

Step 4: Creating Variables

With your partials, you’re now harnessing some of the power of Sass. Your code is more organized, and you’ve dealt with any I-don’t-know-what-this-does-but-I-don’t-want-to-delete-it chunks of CSS. That’s one of the benefits of Sass: it’s primarily a productivity tool, but by using it you pretty much have to write better, more organized code.

It’s the same deal with variables: they help you work faster, and they’ll also help you write better code. Since we’re moving an existing project into CSS, we’re not going to get as many benefits as if we’d started with variables in the first place, but it’s still a helpful, worthwhile endeavor.

So let’s start by using a variable for one of our colors. Most sites have at least one color that’s used more than once. Let’s say that our site uses two colors throughout: #ff5858 and #d7fa97. (Those are the colors used on this site; I couldn’t think of anything else, okay?) We likely use those same hex codes on a bunch of different styles throughout the site. (If you only use them once, a) that’s weird and b) you probably don’t need a variable.)

The first thing we’re going to do is create a new partial file called “_base.scss”. Just create a blank file for now and save it in your partials directory. And then — you guessed it — create an @import statement for this new file. Put this @import statement at the very top of your @import list. You’re going to be using this file to store all your variables, so you’ll want all the rest of the partials to be able to use those variables, and they can only do that if you’ve already imported them.

In your _base.scss file, add these two lines:

$cool-color: #ff5858;
$lame-color: #d7fa97;

(That’s just to show you the syntax. Please don’t use those actual colors. I worked very hard on picking the exact right Late 2014 Pink and Green.)

So what we did there is we created two variables, $cool-color and $lame-color. You can use whatever names you want, although it’s generally a good practice to not call them “pink” and “green.” You can do that, but when you decide that pink is lame and you’re changing it to salmon, you’re going to feel dumb every time you look at your variables.

Now that we have our variables set, we’re going to replace all instances of the color hex code with the variable. That is: everywhere that #ff5858 appears, we’re going to write $cool-color instead. With colors, you can go ahead and use the find-and-replace function to do this. Most text editors will let you find and replace for all files in your partials folder and subfolders. (Just don’t do it for your _base.scss file, obviously.) Do this for both colors, save everything, and go ahead and do the grunt thing in your terminal. There you go! Your end CSS is exactly the same, but you’re now using variables.

At this point, this might seem dumb/like a waste of time. And if you were just doing colors, it would be. One of the big benefits of variables is that if you ever need to change a color (or whatever), you only need to change it in one place and it changes everywhere. But with colors, as we just saw, you could just do that with find-and-replace, which might not make you feel like a true nerd but is nonetheless effective.

I find that variables are more useful with numbers. Let’s say that you have a margin of 20px on an element. Let’s say that you’re also using padding of 20px on another element, because you want it to have a gutter of the same size, but for that one it makes more sense to use padding than margin. In your _base.scss file, you can just set a variable like this:

$gutter: 20px;

And then on both of those elements just use the $gutter variable, e.g.:

margin: $gutter;

Now let’s say that we want to have more space around a certain element. Instead of making up a number, we can make this number double our gutter:

margin: 2*$gutter;

Sass does the math for you — in your CSS, this comes out as:

margin: 40px;

Unlike what we did with colors, we probably don’t want to just find-and-replace all instances of “20px” with $gutter. If you were using a 20px margin as part of your grid system, or if you had a 20px border that was designed to match that $gutter margin, or if you had a DIV that you wanted to be 4 gutters (80px) wide — replace all those with $gutter or a multiple of $gutter. But if you have something with height: 20px, and you can’t figure out why it was 20px, congratulations: you just found a magic number.

<tangent> Re: Magic Numbers

Magic numbers are just that: they’re magic! That is, they’re numbers you probably got by guessing and checking until something looked like it lined up on your screen. Often times they involve text. For example, let’s say that you had a blue bar that you wanted to be exactly the same height as the text next to it, and on your screen 20px makes it look absolutely perfect. Presto! But magic doesn’t work every time: when someone else looks at the page, they can’t load your fancy fonts, or they have something funky going on with their zoom, and your whole layout is broken and you feel the deep shame of a failed magician.

</tangent>

Once you have a set of numbers replaced with a certain variable, you can do math (like we already did with the 2*$gutter), and you can also change the whole thing easily when your boss/client says that they would like just a teensy more space on the site gutters.

 Step 5: The World Is Your Oyster

Now that you have your CSS moved to Sass, you can get cracking on some advanced stuff — if you want to. But it’s important to remember that you don’t have to use all of Sass. It provides a ton of functionality, and you can really do some cool stuff with it, but odds are you don’t need everything that Sass has. So don’t get overwhelmed if you don’t get all of Sass right away — but if you ever find yourself thinking, hey, I wish I could do (something) with CSS, Sass is probably your answer.

That said, here are a few of the things you should definitely look into:

Mixins

Compass

Placeholders

Happy Sassing.