SASS Features

A guide to using SASS features to supercharge your style sheets!

Scroll down...

Content

Resources

Comments

This lesson will take you through the various features that make SASS worthy of its name. We already know what SASS stands for, but how do you make a SASS file?

SASS files are designated by the .scss extension. So basically just changing your file extension to .scss is all it takes! Note: you can also create a file with a .sass extension. It will still be treated as a SASS file, however, they syntax inside needs to be different. It's inspired by languages such as Ruby or Python, such that it's indentation based, it does not support curly braces, etc. Naturally, it appeals more to developers used to those environments and ways of writing code. From now on we will refer only to .scss extension, which looks more like regular CSS (curly braces, indentation is not mandatory, etc.)

Note: Another popular (and very similar) preprocessor you might run into is called LESS. We won't cover it here because frankly, SASS is better (better support from the community, more features in the language, etc.).

In this brief lesson, you'll learn the new functionality that SASS gives you and how to use it. By the end of this unit, your SASSiness will be off the charts!

SASSmograph

Installing and Getting Started with SASS

From reading the SASS documentation, you can see that it's also very simple to use.

# Install SASS (which is a Ruby gem) on your computer.
# You need to have Ruby installed for that
$ gem install sass 

# Convert the input file to the output file.
$ sass input_filename.scss output_filename.css

# Automatically perform the compilation whenever the input file is changed.  
$ sass --watch input_filename.scss:output_filename.css 

# You can also watch an entire directory
$ sass --watch app/sass:public/stylesheets

Try it Out

Create a simple .scss file with some nested styling, for instance:

div.something{
  font-size: 15px;
  h1 {
    color: blue;
  }
}

Then use SASS from the command line to convert it into:

div.something {
  font-size: 15px; }
  div.something h1 {
    color: blue; }

...which, if we space it out, is just the CSS we would have otherwise written in multiple lines:

div.something {
  font-size: 15px; 
}
div.something h1 {
    color: blue; 
}

Keep playing around with it. When you're first starting out, it may seem like you're not really saving much time but when you start working with real-life sites, you'll learn to love nesting your selectors and strategically use variables and @imports.

Pretty cool, huh?

Features of SASS

Ok, so let's talk a bit about the features of SASS. For a more extensive list, please make sure you check out the official docs.

SASS essentially gives you a lot of the benefits of working with code but for stylesheets. It has variables, functions and modules that can be imported and re-used. You can iterate, use conditional logic, extend existing selector styles. Best of all, you can nest your CSS. It contains a surprisingly deep feature set but you'll get good value out of just the half-dozen main features that they advertise on their website.

A brief skim over the SASS guide will get you started, but let's address the each of the major features of SASS one by one from the docs.

Nesting, Variables and Math

Nesting, variables and math... oh my! We'll begin with nesting rules first.

Nesting rules (and nesting does rule) is about as amazing as it sounds coming from CSS. Remember all those times where you had to repeat the same order of nested selectors to target the same elements in your raw CSS files? Well no more! SASS allows you to nest CSS selectors within selectors like you'd expect. Soon you'll wonder how you lived without this feature!

Here is an example:

#main p {
  color: #00ff00;
  width: 97%;

  .redbox {
    background-color: #ff0000;
    color: #000000;
  }
}

Once the SASS preprocessor is run and this compiles you'll get this lovely CSS output:

#main p {
  color: #00ff00;
  width: 97%; }
  #main p .redbox {
    background-color: #ff0000;
    color: #000000; }

Notice how you didn't have to write #main p twice! Now just multiply that by how many style sheets and selectors you've written and will write. How did you live without this?!

Variables are another killer feature of SASS. Remember when you wanted to change the primary color of your color scheme in all of your CSS for your entire project?

CSS color changing please no

(Note: CSS has long been tweaking the idea of bringing variables into the language. Although things are not yet standardized - you can check out more info here - there are already browsers which support that.)

SASS give you variables out of the box. With SASS you'll never need to worry about making changes to files and selectors one by one by one by... you know... you've been there! SASS variables are just awesome. Probably where they got part of the name from! How do they work?

Variables in SASS work much like variables in any programming language. They have a name and are assigned to a value. The syntax for doing this is:

$width: 5em;

You must prefix all variables with the dollar sign. You also must use the colon instead of the equals sign for assignment in SASS.

It is also important to know which types of values or "data types" variables can have in SASS. You can read up on those in the docs here.

SASS is also loaded with various ways you can use operators. Here is a little taste of the possibilities:

p {
  font: 10px/8px;             /* Plain CSS, no division */
  $width: 1000px;
  width: $width/2;            /* Uses a variable, does division */
  width: round(1.5)/2;        /* Uses a function, does division */
  height: (500px/2);          /* Uses parentheses, does division */
  margin-left: 5px + 8px/2px; /* Uses +, does division */
  font: (italic bold 10px/8px); /* In a list, parentheses don't count */
}

Combining CSS Files with @import

Importing files with SASS is made super easy with the @import directive. You can provide the @import directive with a comma separated list of SASS files to combine into a single file and SASS will compile them all to CSS. Here is an example:

@import "rounded-corners", "text-shadow";

More info about the import directive here.

Re-using Styles with Mixins

Mixins is a feature in SASS that allows you to create reusable chunks of CSS. These chunks of CSS are easily reused in various ways via the @include mixin-name; syntax. They are actually very similar to a JavaScript function which can be called in different parts of your program (more on that later). Here is a full example:

@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}
.page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

This SASS compiles to the following CSS:

.page-title {
  font-family: Arial;
  font-size: 20px;
  font-weight: bold;
  color: #ff0000;
  padding: 4px;
  margin-top: 10px; }

Imagine all the DRYness (DRY stands for "Don't Repeat Yourself", which is a good programming principle to obey at all times) you can create with SASS mixins! No longer will you have to copy and paste tons of CSS to make reusable components.

Extending Styles with Inheritance

Extending styles gives you the power to take existing SASS and CSS and plug it into your own styles. This feature makes it possible for you to not only DRY up a single project, but multiple projects in that you can import style sheets and simply extend existing classes to suit your needs! Let's see it in action.

Here we see a simple class for an error message extended to have more emphasis:

.error {
  border: 1px #f00;
  background-color: #fdd;
}
.serious-error {
  @extend .error;
  border-width: 3px;
}

This compiles to:

.error, .serious-error {
  border: 1px #f00;
  background-color: #fdd;
}

.serious-error {
  border-width: 3px;
}

As you can see and imagine, this feature becomes extremely useful when adding your own styles to existing CSS. This can be done for your own styles or style sheets that you've imported from a third party!

SASS Best Practices

While SASS makes your style sheets awesome it doesn't do all the work for you. You'll still have to avoid pitfalls that will make your SASS more difficult to manage. Here are a few to remember:

  1. Structure your SASS projects: Use sub folders and partial files to organize code semantically.
  2. Avoid vague variable names: Use variable names that are meaningful to your project. For example, $color-primary instead of $blue (this also prepares you in case the colors will change in the future).
  3. Use nesting and looping to your advantage: It can be very useful to use nesting to visually make your style sheets easier to read. Looping can help reduce otherwise repetitive code for creating increasing and decreasing sizes in widths, heights and fonts.
  4. Keep your @include and @extend statements above the CSS: When you write SASS write any raw CSS below the @include and @extend statements in the selector.
  5. Use $kebab-case when naming variables, functions and mixins: Stick with the convention of CSS. CSS doesn't use camelCase so don't use it in your SASS!

Be sure to check out the additional resources to see more links with SASS best practices and style guides.

Code Review

The important bits of code from this lesson

/* Using SASS to nest selectors */

#main p {
  color: #00ff00;
  width: 97%;

  .redbox {
    background-color: #ff0000;
    color: #000000;
  }
}


/* Creating SASS variables */
$width: 5em;

/* Using SASS operators to perform */
/* math on CSS units */
p {
  font: 10px/8px;             // Plain CSS, no division
  $width: 1000px;
  width: $width/2;            // Uses a variable, does division
  width: round(1.5)/2;        // Uses a function, does division
  height: (500px/2);          // Uses parentheses, does division
  margin-left: 5px + 8px/2px; // Uses +, does division
  font: (italic bold 10px/8px); // In a list, parentheses don't count
}

/* Using @import to combine style sheets */

@import "rounded-corners", "text-shadow";


/* Creating a @mixin */

@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}
.page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

/* Using @extend */

.error {
  border: 1px #f00;
  background-color: #fdd;
}
.serious-error {
  @extend .error;
  border-width: 3px;
}


/* Set a variable to avoid hard-coding*/
$base-font-size: 18px;

/* Use nesting and variables */
.post-container {
  p{
    font-size: $base-font-size;
  }
  li{
    font-size: $base-font-size;
  }

  /* Do some math */
  strong{
    font-weight: bold;
    font-size: $base-font-size + 2px;
  }
}

/* Set up a mix-in (method) to avoid writing lots of prefixes */
@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
     -moz-border-radius: $radius;
      -ms-border-radius: $radius;
          border-radius: $radius;
}

/* Use the mixin later in the code */
.rounded-box { 
  @include border-radius(10px); 
}

/* Keep code DRY with extensions */
.message {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}
.success {
  /* it's like pasting all the code from .message here */
  @extend .message;  
  border-color: green;
}

Wrapping Up

It'll feel a bit awkward to set up SASS at first (e.g. getting it to automatically re-compile your CSS) but it will quickly become a part of the background. In most of the tools/frameworks out there, SASS support and the ability to compile SASS to CSS are already built-in features.

In the upcoming projects, you'll get plenty of opportunities to take advantage of the time-saving features of SASS. As we said, you'll likely find yourself sticking to the basic nesting and variables at first but those alone are well worth diving into SASS for.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

Sorry, comments aren't active just yet!

Next Lesson: Test Yourself: SASS Preprocessing