Getting Started with Sass & Compass: Part 1

When i started learning Sass, i could not find a simple and clear tutorial and i had to dig into several sites & posts. I also see developers struggling when starting to learn Sass and usually they tend to give up.
So i wrote this article hoping it will help people speed things up.

SO, FIRST THINGS FIRST: WHAT IS SASS?

Sass is a pre-processor for CSS. This means that Sass compiles into CSS. Pre-processors extend CSS with variables, operators, interpolations, functions, mixins and many more other usable assets. SASS, LESS and Stylus are the most popular among developers.

Sass is completely compatible with all versions of CSS and has a large community, which means that is actively supported.

SO, WHY A PRE-PROCESSOR?

Well, people that are using pre-processors cannot even think of working without them.

  • You get to write less code and sass does all the handling.
  • You do not need to worry about prefixes. You just need to write one single command instead of having to remember all prefixes.
  • You can write a more structured code
  • You can even split your css file into multiple smaller ones that makes it easy to find and maintain your code. Sass will compile it into one css file.
  • Increases your productivity.
  • Minifies your code automatically.

HOW TO GET STARTED

You are going to need Ruby to use Sass.
Do not fear, its very easy to install:

Visit https://rubyinstaller.org/ download the installer and run it.
Mac computers will most likely have ruby pre-installed.

After installing Ruby, open your command line (for Windows you just type cmd in the search bar).

On the command line type:

gem install sass

That’s it!

SYNTAX

There are two syntaxes available for Sass:

The first, known as SCSS (Sassy CSS) is used throughout this post and is also the newest syntax. SCSS is an extension of the syntax of CSS. This means that every valid CSS stylesheet is a valid SCSS file with the same meaning. Additionally, SCSS understands most CSS hacks and vendor-specific syntax. Files using this syntax have the .scss extension.

The second and older syntax, known as the indented syntax (or sometimes just “Sass“), provides a more concise way of writing CSS. It uses indentation rather than brackets to indicate nesting of selectors, and newlines rather than semicolons to separate properties. Files using this syntax have the .sass extension.

Either syntax can import files written in the other. Files can be automatically converted from one syntax to the other using the sass-convert command line tool:

# to Convert Sass to SCSS type in your command line:
$ sass-convert style.sass style.scss

# to Convert SCSS to Sass:
$ sass-convert style.scss style.sass

I know that this may look intimidating, but fear not!

For this tutorial we will be using the SCSS syntax. It is easier for everyone to grasp, plus you may convert any CSS file into SCSS: just rename the file from .css to .scss

To compile a sass file to CSS:

sass input.scss output.css

NESTING

With a pre-processor you can nest your rules. This means that you can place a rule inside another. The inner rule then only applies within the outer rule’s selector. For example:

a{
   color: green;
   
   &:hover{
      color: orange;
   }
 }

Will compile to:

a{ 
   color: green;
}
a:hover{ 
   color: orange; 
}

and

.header{
   color: #fff;
 
   .link{
      color: blue;
   }
}

Will compile to:

.header{
   color: #fff;
 }
 .header .link{
   color: blue;
 }

The & selector is referring to the parent selector, so

a {
  color: red;
  
  &:hover { color: green; }
  .header & { color: blue; }
}

is compiled to:

a {
   color: red;
}
a:hover {
   color: green; 
}
.header a {
   color: blue;
}

I do have to point out here, that nesting is not something you should use extensively. It can produce a large css file with nested rules that you do not really need.

You should only nest the rules that you need to. To keep your code organized try BEM instead.

VARIABLES

Variables are a way to store information that you want to reuse throughout your stylesheet. 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.


$max_width: 800px;
$yellow: #F3E05E;

.div{
   max-width: $max_width;
   color: $yellow;
}

Will compile to:


.div{
   max-width: 800px;
   color: #F3E05E;
}

PARTIALS

If you split your CSS code into several CSS files it is going to be easier for you, even if you don’t think so at first:

  • You will no longer search through a huge CSS file to find a rule,
  • your code will be easier to maintain,
  • it is a great way to modularize your CSS.

These files are called Partials. A partial is a Sass file named with a leading underscore, for example _colors.scss. The underscore lets Sass know that the file is only a partial file and that it should not compile into a CSS file. Sass partials are included into the main Sass file with the @import directive.

@import '_colors';

You do not need to include the file extension. Any code that you have in the partial file will be placed in the main css file, at the place of the @import.

MIXINS

A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. For example the prefixes needed in CSS3 are hard to remember or you can get bored of typing them every time. Also if a prefix gets changed, you will have to go throughout your CSS file and make the update manually. Instead, you can use a mixin :


@mixin border-radius($radius: 50%) {
  -webkit-border-radius: $radius;
     -moz-border-radius: $radius;
      -ms-border-radius: $radius;
          border-radius: $radius;
}

.box { @include border-radius(10px); }

will compile to:


.box {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -ms-border-radius: 10px;
  border-radius: 10px;
}

A mixin that i also use:


@mixin text-selection($bgcolor, $color){
    ::-moz-selection{
        background-color: $bgcolor;
        color: $color;
    }
    ::selection{
        background-color: $bgcolor;
        color: $color;
    }
}

@include text-selection(#f0f, #222);

Will compile to:


::-moz-selection{
    background-color: #f0f ;
    color: #222;
}
::selection{
    background-color: #f0f ;
    color: #222;
}

A mixin can also have multiple parameters, just by using the … after the main parameter.


@mixin box-shadow($shadows...) {
  -moz-box-shadow: $shadows;
  -webkit-box-shadow: $shadows;
  box-shadow: $shadows;
}

.shadows {
  @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}

FUNCTIONS

You may create your own functions, to generate a value, for example:


@function set-notification-text-color($color) {
  @if (lightness($color) > 50) {
    @return #000; // Lighter background, return dark color
  } @else {
    @return #fff; // Darker background, return light color
  }
}

Sass has its own set of functions to make your life easier.

OPERATORS & MATH IN SASS

Doing math in your CSS is very helpful to calculate values. Sass has a handful of standard math operators like +, -, *, /, and %. for example:/p>


$grid_width: 960px;

.div{
  width: 300px / $grid_width * 100%;
}

Will generate:


.div{
  width: 31.25%;
}

EXTEND


.button{
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.error {
  @extend .button;
  border-color: red;
}
.warning{
  @extend .button;
  border-color: orange;
}

The above code takes the CSS properties in .button and applies them to .error:


.button, .error, .warning{
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.error {
  border-color: red;
}
.warning{
  border-color: orange;
}

PLACEHOLDER SELECTORS %

The extend as explained above will merge all class names into 1 ruleset, including the main one, in our case .button

In cases where we never use the .button class in our code, there is no need to be present in the css. In this case we can use a placeholder instead. Placeholder selectors have the additional property that they will not show up in the generated CSS, only the selectors that extend them will be included in the output. The above example would then turn into:


%button{
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.error {
  @extend %button;
  border-color: red;
}
.warning{
  @extend %button;
  border-color: orange;
}

Will compile to:


.error, .warning{
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.error {
  border-color: red;
}
.warning{
  border-color: orange;
}

You may find some more examples about this and differences between @extend and @include here.

#{} INTERPOLATION

There are cases when you will need to produce dynamic content. This can be achieved with interpolation. For example:


@mixin element_content($element, $content: '') {
  #{$element}:before {
    content: $content;
    position: absolute;
  }
}

@include element_content(".header", 'Hello dear guest!');

is compiled to:


.header:before {
    content: 'Hello dear guest!';
    position: absolute;
}

So the #{$element} will be replaced by your element, .header

IF / FOR / EACH / WHILE DIRECTIVES

In Sass you may use directives almost the same way you would in php or javascript:

@if


$color: blue;
@if (lightness($color) > 50) {
    background: #000; // Lighter background, return dark color
} @else {
    background: #fff; // Darker background, return light color
}

@for


@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}

@each


@each $animal in puma, sea-slug, egret, salamander {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
  }
}

In the above example the puma, sea-slug, egret, salamander is a list. A more complicated example with an array:


@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {
  #{$header} {
    font-size: $size;
  }
}

which is compiled to:


h1 {
  font-size: 2em; }
h2 {
  font-size: 1.5em; }
h3 {
  font-size: 1.2em; }

@while


$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}

ADDITIONAL REFERENCES:

Continue reading: Getting Started with Sass & Compass: Part 2