If you write a lot of code on CSS, preprocessor can save you a lot of nerves and time. Using Sass , Less , Stylus or PostCSS (post-processor) to make large and complex style sheets becomes much easier and clearer. Sass makes CSS fun again. Sass is an extension of CSS, adding nested rules, variables, mixins, selector inheritance and more. It’s translated to well-formatted, standard CSS using the command line tool or a plugin for your build system. Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons. This tutorial is written using SCSS. If you’re already familiar with CSS3, you’ll be able to pick up Sass relatively quickly. It does not provide any new styling properties but rather the tools to write your CSS more efficiently and make maintenance much easier. If you never approached any preprocessor, don’t worry we will explain what they are and how they work. There are many CSS preprocessor you can use. For example Sass, Stylus or LESS. Even they might differ from each other in syntax, they all share common philosophy – DRY – Don’t Repeat Yourself. Their goal is to help you by making your work-flow easier and more managable. This is also the reason why I chose to write a tutorial on Sass as first (LESS and Stylus will follow). We hope that it will help you get your job done faster, with less stress and more fun. Take a look at them and choose the one you like, however we recommend you - for your future work as Web Designer or Developer - to brush your skills and became more familiar with command line. It is not that hard.

Install Sass

There are 2 ways to install Sass.

1. APPLICATION

There are a good many applications that will get you up and running with Sass in a few minutes for Mac, Windows, and Linux. You can download most of the applications for free but a few of them are paid apps.

 CodeKit (Paid) Mac  Compass.app (Paid, Open Source) Mac Windows Linux  Ghostlab (Paid) Mac Windows  Koala (Open Source) Mac Windows Linux  LiveReload (Paid, Open Source) Mac Windows  Prepros (Paid) Mac Windows Linux  Scout-App (Free, Open Source) Windows Linux Mac 2. COMMAND LINE

1. Get started with Sass

First install Sass using one of the options below, then run sass --version to be sure it installed correctly. You can also run sass --help for more information about the command-line interface.

If you are using Mac, you already have Ruby so you can open your command line and type command for Mac. For PC, first you need to get Ruby.

After installing Ruby you will open your command line and type:

PC:

gem install sass

MAC:

sudo gem install sass Install Anywhere (Standalone) Also you can install Sass on Windows, Mac, or Linux by downloading the package for your operating system from GitHub. That's all—there are no external dependencies and nothing else you need to install.

Install Anywhere ()

If you use Node.js, you can also install Sass using npm by running

npm install -g sass

However, please note that this will install the pure JavaScript implementation of Sass, which runs somewhat slower than the other options listed here. But it has the same interface, so it’ll be easy to swap in another implementation later if you need a bit more speed!

Install on Windows (Chocolatey)

If you use the Chocolatey package manager for Windows, you can install Dart Sass by running

choco install sass

Install on Mac OS X (Homebrew)

If you use the Homebrew package manager for Mac OS X, you can install Dart Sass by running

brew install sass/sass/sass When you install Sass on the command line, you'll be able to run the sass executable to compile .sass and .scss files to . files.

Once you start tinkering with Sass, it will take your preprocessed Sass file and save it as a normal CSS file that you can use in your website.

The most direct way to make this happen is in your terminal. Once Sass is installed, you can compile your Sass to CSS using the scss command. You'll need to tell Sass which file to build from, and where to output CSS to. For example, running sass input.scss output.css from your terminal would take a single Sass file, input.scss, and compile that file to output.css. ou can also watch individual files or directories with the --watch flag. The watch flag tells Sass to watch your source files for changes, and re-compile CSS each time you save your Sass. If you wanted to watch (instead of manually build) your input.scss file, you'd just add the watch flag to your command, like so:

sass --watch input.scss:output.css

You can watch and output to directories by using folder paths as your input and output, and separating them with a colon. In this example:

sass --watch app/scss:public/stylesheets

Sass would watch all files in the app/sass folder for changes, and compile CSS to the public/stylesheets folder. 2. Variables

Variables work in exactly the same way you saw in every other programming language. When declaring, we store a specific value in it, which we usually see in CSS like color, font or any other property. Think of variables as a way to store information that you want to reuse throughout your stylesheets. You can store things like colors, font stacks, or any CSS value you think you'll want to reuse. Sass uses the $ symbol to make something a variable. Here's an example:

SCSS:

$font-stack: Helvetica, sans-serif; $primary-color: #333;

body { font: 100% $font-stack; color: $primary-color; }

CSS:

body { font: 100% Helvetica, sans-serif; color: #333; }

When the Sass is processed, it takes the variables we define for the $font- stack and $primary-color and outputs normal CSS with our variable values placed in the CSS. This can be extremely powerful when working with brand colors and keeping them consistent throughout the site. 3. Nesting

If you are familiar with HTML (which you already should), you’ve probably noticed its nested hierarchy. Elements are nested inside each other, from parent to child. CSS has no clue about this feature. Through Sass you can nest your CSS selectors in the same way as you do it with your HTML code and create clean visual hierarchy of selectors and their rules. This feature comes very handy for managing :hover, :focus, :active and other states. To nest these states you write it inside the selector and replace the selector before colon with & symbol.

Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. Be aware that overly nested rules will result in over- qualified CSS that could prove hard to maintain and is generally considered bad practice.

SCSS:

nav { ul { margin: 0; padding: 0; list-style: none; }

li { display: inline-block; }

a { display: block; padding: 6px 12px; text-decoration: none; &:hover { color: #ddd; } } } CSS:

nav ul { margin: 0; padding: 0; list-style: none; }

nav li { display: inline-block; }

nav a { display: block; padding: 6px 12px; text-decoration: none; }

nav a:hover { color: #ddd; }

You'll notice that the ul, li, and a selectors are nested inside the nav selector. This is a great way to organize your CSS and make it more readable. Very neat and conflict proof.

4. Partials

You can create partial Sass files that contain little snippets of CSS that you can include in other Sass files. This is a great way to modularize your CSS and help keep things easier to maintain. A partial is a Sass file named with a leading underscore. You might name it something like _partial.scss The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @use rule. 5. Modules

You don't have to write all your Sass in a single file. You can split it up however you want with the @use rule. This rule loads another Sass file as a module, which means you can refer to its variables, mixins, and functions in your Sass file with a name-space based on the filename. Using a file will also include the CSS it generates in your compiled output!

SCSS:

// _base.scss

$font-stack: Helvetica, sans-serif; $primary-color: #333;

body { font: 100% $font-stack; color: $primary-color; }

// _styles.scss

@use 'base';

.inverse { background-color: base.$primary-color; color: white; } CSS:

body { font: 100% Helvetica, sans-serif; color: #333; }

.inverse { background-color: #333; color: white; }

Notice we're using @use 'base'; in the styles.scss file. When you use a file you don't need to include the file extension. Sass is smart and will figure it out for you.

6. Mixins

Some things in CSS are a bit tedious to write, especially with CSS3 and the many vendor prefixes that exist. A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. You can even pass in values to make your mixin more flexible. A good use of a mixin is for vendor prefixes. Here's an example for transform.

SCSS:

@mixin transform($property) { -webkit-transform: $property; -ms-transform: $property; transform: $property; }

.box { @include transform(rotate(30deg)); } CSS:

.box { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); }

To create a mixin you use the @mixin directive and give it a name. We've named our mixin transform. We're also using the variable $property inside the parentheses so we can pass in a transform of whatever we want. After you create your mixin, you can then use it as a CSS declaration starting with @include followed by the name of the mixin.

7. Extend/Inheritance

This is one of the most useful features of Sass. Using @extend lets you share a set of CSS properties from one selector to another. It helps keep your Sass very DRY. In our example we're going to create a simple series of messaging for errors, warnings and successes using another feature which goes hand in hand with extend, placeholder classes. A placeholder class is a special type of class that only prints when it is extended, and can help keep your compiled CSS neat and clean.

SCSS:

// This CSS will print because %message-shared is extended. %message-shared { border: solid 1px #ccc; padding: 10px; color: #333; } // This CSS won’t print because %equal-height is never extended. %equal-heights { display: flex; flex-wrap: wrap; }

.message { @extend %message-shared; }

.success { @extend %message-shared; border-color: green; }

.error { @extend %message-shared; border-color: red; }

.warning { @extend %message-shared; border-color: yellow; }

CSS:

// This CSS will print because %message-shared is extended. .message, .success, .error, .warning { border: 1px solid #ccc; padding: 10px; color: #333; } .success { border-color: green; }

.error { border-color: red; }

.warning { border-color: yellow; }

What the above code does is tells .message, .success, .error, and .warning to behave just like %message-shared. That means anywhere that %message- shared shows up, .message, .success, .error, & .warning will too. The magic happens in the generated CSS, where each of these classes will get the same CSS properties as %message-shared. This helps you avoid having to write multiple class names on HTML elements.

You can extend most simple CSS selectors in addition to placeholder classes in Sass, but using placeholders is the easiest way to make sure you aren't extending a class that's nested elsewhere in your styles, which can result in unintended selectors in your CSS.

Note that the CSS in %equal-heights isn't generated, because %equal-heights is never extended.

8. Operators

Doing math in your CSS is very helpful. Sass has a handful of standard math operators like +, -, *, /, and %. In our example we're going to do some simple math to calculate widths for an aside & article. SCSS:

.container { width: 100%; } article[role=”main”] { float: left; width: 600px / 960px * 100%; } aside[role=”complementary”] { float: right; width: 300px / 960px * 100%; }

CSS:

.container { width: 100%; } article[role=”main”] { float: left; width: 62.5%; } aside[role=”complementary”] { float: right; width: 31.25%; }

We've created a very simple fluid grid, based on 960px. Operations in Sass let us do something like take pixel values and convert them to percentages without much hassle. 9. The default Flag

This flag allows us to set the value of a variable in case it hasn’t already been set or its current value is null (treated as unassigned). To better explain how we can take advantage of it in a real scenario, let’s suppose that we have a project with the following structure:

1 Project-Name/ 2 ├── ... 3 ├── css/ 4 │ └── custom.css 5 └── scss/ 6 ├── _config.scss 7 ├── _variables.scss 8 ├── _mixins.scss 9 └── custom.css

The app.scss file looks like this:

@import ”config”; @import ”variable”; @import ”mixins”;

button { @include button-style; }

// more style

Let’s see the contents of the partial files. Firstly, the variables.scss file contains our variables:

$btn-bg-color: lightblue !default; $btn-bg-color-hover: darken($btn-bg-color, 5%);

// more variables

Notice the the default flag assigned to the btn-bg-color variable.

Secondly, the mixins.scss file include our mixins:

@mixin button-style ($bg-color: $btn-bg-color, $bg-color-hover: $btn-bg-color-hover) { background-color: $bg-color; // more styles

&:hover { background-color: $bg-color-hover; // more styles } }

// more mixins

Then, the generated app.scss file will be as follows:

button { color: lightblue; } button:hover { background-color: #99cfe0; } So, our buttons come with default styles. But let’s suppose that we want to have the option to overwrite then by applying our custom values. To do this, we can reassign the desired (default) variable in the config.scss partial file:

$btn-bg-color: chocolate;

// more variables

Setting the value of the variable to chocolate will result in ignoring the corresponding value ( lightblue ) that has received the default flag. Therefore, the generated CSS changes as we can see below:

button { color: chocolate; } button:hover { background-color: #bc5e1b; }

Note: in case we haven’t added the default flag to the btn-bg-color variable, our CSS would be, due to the cascading nature of CSS, as follows:

button { color: lightblue; }

// hover styles 10. The global Flag

This second flag helps us change the scope of a local variable.

Do you remember the error we saw in our first example? Well, that happened because we tried to use the btn-bg-color variable in the .wrap selector. Let’s modify our example to include this new flag. Here are the new styles:

@mixin button-style { $btn-bg-color: lightblue !global; color: $btn-bg-color; }

button { @include button-style; }

.wrap { backgound: $btn-bg-color; }

As you can see below, thanks to this flag, the CSS compiles without any errors:

button { color: lightblue; }

.wrap { background: lightblue; }

The global flag is useful, but bear in mind that it’s not always good practice to change a variable’s scope. 11. Breakpoints

When Sass 3.2 was released some time ago, they made it possible to define names to our media queries, which makes the usage of them a lot cleaner. Instead of calling them @media (min-width: 600px) we can give them more semantic names like “breakpoint-large” or “breakpoint-a-really-large-computer- machine”.

@mixin bp-large { @media only screen and (max-width: 60em) { @content; } } @mixin bp-medium { @media only screen and (max-width: 40em) { @content; } } @mixin bp-small { @media only screen and (max-width: 30em) { @content; } }

SCSS:

.sidebar { width: 60%; float: left; @include bp-small { width: 100%; float: none; } } CSS:

.sidebar { width: 60%; float: left; @media only screen and (max-width: 30em) { .sidebar { width: 100%; float: none; } } }

12. Checking if a Variable Exists

Sass provides two introspection functions for testing whether a variable exists or not. We can use the and/or functions to check if our local and/or global variables exists respectively.

For example, here’s a common use case where we define a variable containing the absolute path to a Google Font. Then, we choose to import that font in our stylesheets, but only if the relevant variable has been instantiated.

$google-font: "http://fonts.googleapis.com/css?family=Alegreya";

@if (global-variable-exists(google-font)) { @import url($google-font); }

The result:

@import url("http://fonts.googleapis.com/css?family=Alegreya");