2Compiling Sass into CSS

We’ve introduced the idea that Sass is an advanced version of CSS. As a matter of fact, any valid CSS is valid Sass. Sass just adds features on top of CSS—it’s a kind of meta language. Unfortunately at this point, no browsers support Sass files directly, so we have to convert from Sass into CSS first.

The basic gist is that we write some Sass and then we compile—or convert—Sass into CSS. How do we compile Sass into CSS? Well, you did it in the last step of Task 1, Installing Sass, but we didn’t use any of the extra powers of Sass, so the results were pretty similar.

Let’s run through how we can convert a Sass file into a CSS file again in a lot more detail than we did in the last task.

First, we need to create a Sass file. Any old thing will do—this is just to show how we can turn our Sass into CSS. Since CSS is valid Sass, take any random CSS file you have sitting around and change its extension to scss.

Now, let’s go to our command line. Type sass, followed by the name of your file.

Look at that! Oh right, it just printed out the CSS but in a different format. And printing out your CSS files to the console isn’t very useful. It would be better if we could make a separate CSS file.

Well, you can! Run the sass command again with a second argument that specifies the output file you want. For instance, you might say sass test.scss test.css and Sass will generate a CSS file named test.css.

Running that command over and over would be extremely tedious as we edit our Sass file. If you are using Rails or another framework, it can automatically update your CSS for you. But when we aren’t using a framework, we have a neat command-line trick for converting Sass files into CSS files as we alter them. It’s called watch.

watch will take any scss file found in the specified Sass folder and convert it into a css file in the specified CSS folder. Magic! It doesn’t just do this once either. It constantly watches the file for any changes and incorporates them into the CSS file.

Another useful command to mention here is convert. You can use this to turn a css file into a sass or scss file.

What To Do...
  • Start with a simple bit of Sass.
     
    .fab_text {
     
    color: #336699;
     
    font-size: 2em;
     
    }
  • Type this in your command line.
     
    sass fabtext.scss

    You should see the following:

     
    .fab_text {
     
    color: ​#336699;
     
    font-size: 2em; }
  • Watch a folder.

    Assuming we have a Sass and a CSS folder, the command would look like this:

     
    sass --watch stylesheets/sass:stylesheets/css
  • Convert a CSS file to a Sass file.
     
    sass convert test.css test.sass

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset