Lesson 2 - Introduction to the Sass CSS preprocessor

HTML and CSS Modern and professional web portfolio Introduction to the Sass CSS preprocessor

Sass is a compiled language extending CSS syntax of variables, loops, if-statements, mixins, functions, and more. It saves time, allows to write shorter code, it's more readable and easier to maintain.

As we discussed in the previous lesson, Preparations and configuration, we're going to use SCSS syntax (Sassy CSS) which is an extension of the CSS syntax - meaning that every CSS code is compatible with SCSS (this doesn't apply the other way).

Every time you create a SCSS file, you have to compile it into CSS using the Sass compiler which we've already installed together with Ruby in the previous lesson. SCSS files cannot be executed, because the browser doesn't know this syntax so it can't use it to style elements.

You can find all the information, documentation and code examples at the official website http://sass-lang.com

What are the advantages of using a preprocessor, in this case Sass, then? Let's go through them and show some examples.

Comments

In Sass, we can use two types of comments. The first type is the classic comment from CSS, /* ... /* will be kept after the compilation and will appear in the same way in the final CSS file. The second type, // ..., won't be compiled so you can use such comments only in SCSS files.

Nesting

Nesting is a code style, which enables to nest CSS styles in each other. We can specify element children similarly as we specify properties. This is an extremely useful preprocessor function because it saves lots of trouble with naming dozens of selectors... Nesting can be applied in any way and how many times we want, of course, however, the best practice is to apply the unwritten rule of keeping the number of nested elements up to 4.

Here, we can also use the & keyword, which is a reference to the parent element. We can easily nest hover styles like this for example.

Consider we have a <div> with a paragraph inside. We want a hover effect on the paragraph, but only if it's in a <div>. We can style it like this:

div
{
   background: white;
   width: 900px;
   margin: 0 auto;
   padding: 5px 10px;
   border: 1px solid #ccc;
   p
   {
      color: gray;
      font-family: 'Arvo', serif;
      &:hover
      {
         color: black;
      }
   }
}

As you surely noticed, the code became more organized and shorter compared to pure CSS.

Variables

Variables are effective when we don't want to lose time rewriting values in the whole code, which is kind of annoying in CSS. In Sass, every variable starts with the $ keyword , after which the name-of-the-variable, a colon and the value follows.

It's worth mentioning that if we modify the value of a variable inside a selector, the change will apply to the whole code.

*Let's create some variables for the color, font, width and padding. Afterwards, we'll apply the variables on the <div> and the paragraph from the previous example.

$root-color: gray;
$secondary-color: black;

$div-background: white;
$div-width: 900px;
$div-padding: 5px;
$div-border-color: #ccc;

$paragraph-font: 'Arvo', serif;

div
{
   background: $div-background;
   width: $div-width;
   margin: 0 auto;
   padding: $div-padding $div-padding*2;
   border: 1px solid $div-border-color;
   p
   {
      color: $root-color;
      font-family: $paragraph-font;
      &:hover
      {
         color: $secondary-color;
      }
   }
}

Okay, it may seem to be unnecessarily now, but wait until you try to use variables on a CSS code hundreds lines long :)

Compilation - different output styles

Sass supports several output styles of the exported CSS file - in other words, of the ways that the CSS code will be generated. Every style will be shown on our sample code again.

Compressed

Everything is reduced into a single line without spaces. Just add --style compressed into the argument in PhpStorm or Sublime Text.

div{background:#fff;width:900px;margin:0 auto;padding:5px 10px;border:1px solid #ccc}div p{color:gray;font-family:"Arvo",serif}div p:hover{color:#000}

Compact

Styles will be organized, one selector per line. Lines with the same parent are separated by an empty line.

div { background: white; width: 900px; margin: 0 auto; padding: 5px 10px; border: 1px solid #ccc; }
div p { color: gray; font-family: "Arvo", serif; }
div p:hover { color: black; }

Nested

Creates a usually-formatted CSS. Lines with the same parent are separated by empty lines as with the Compact style and additionally, child selectors are indented.

div {
  background: white;
  width: 900px;
  margin: 0 auto;
  padding: 5px 10px;
  border: 1px solid #ccc; }
  div p {
    color: gray;
    font-family: "Arvo", serif; }
    div p:hover {
      color: black; }

Expanded

The last output style differs from the Nested style in unindented child selectors.

div {
  background: white;
  width: 900px;
  margin: 0 auto;
  padding: 5px 10px;
  border: 1px solid #ccc;
}
div p {
  color: gray;
  font-family: "Arvo", serif;
}
div p:hover {
  color: black;
}

Partials and @import

Sass supports so-called partials. Those are files that are not intended for direct compilation, even though they contain SCSS code. Those files are usually named as _filename.scss. The underscore indicates that this file shouldn't be compiled.

Partials can be imported into our "primary" or grouping SCSS files. To do that, we use the @import keyword. Importing should be done outside our styles, on the very top of our file.

We write the name of the file after the @import keyword, eventually with its subfolder. It's enough to just type filename, but there're different options as well.

@import "_filename.scss";

@import "filename.scss";

@import "_filename";

@import "filename";

If we had our partials in a subfolder, we could specify it like this (you can use different styles, as shown above).

@import "folder/filename";

Mixins

Mixins are parts of code that repeat a lot. We can also pass some input parameters to them. They're used when we want to write some code more times, e.g. for vendor prefixes.

To define a mixin, we use the @mixin keyword, followed by mixin-name and eventually its parameters in parentheses. To call a mixin, we use the @include keyword, followed by mixin-name and eventually parameters in parentheses.

Mixins are usually defined on the top of the file, since we can call them only after they are defined. I recommend to create partials for mixins and call them using @import.

Let's show an example on a mixin that adds vendor prefixes to the border-radius property.

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

.rounded
{
   @include border-radius(7px); //calling the mixin
   // ... the rest of the styles
}

Functions

We use functions when we want to get a particular value from some input parameters. A function returns a value.

@function my-calculation($first-number, $second-number){
  @return ($first-number + $second-number) * 3;
}

Extension

Extensions allow us to reuse the styles of already existing selectors. We used it by the @extend keyword, followed by selector-name, whose style we want to use. Basically, the current selector will be added to the style it inherits from. The best practice is to call extensions at the bottom of the current selector' styles.

We can also use a special selector, the placeholder selector, for inheritance. We use the % keyword similarly as the dot (.) or hashtag (#) we use for class or ID selectors...

Let's show an example.

%width
{
   width: 500px;
}

div
{
   color: red;
   @extend %width;
}

p{
   color: blue;
   @extend %width;
}

The output after the compilation follows.

div, p
{
   width: 500px;
}

div
{
   color: red;
}

p
{
   color: blue;
}

Math operations

Math was always something CSS lacked. We don't have to set fixed values in Sass anymore. Miracles can be done when combining math with variables. We can easily add, subtract, multiply, divide, work with percentage etc.

Basic math operations

width: (100% / 3) ;

width: 300px / 960px * 100%;

If-statements

Applying styles based on conditions is sometimes useful; the best is to combine it with a mixin or a function. There are special characters used in the condition, for example < (less than), > (greater than), == (equals), != (not equal) etc.

@if keyword applies to the first case, @else if to another case, @else to the rest of the cases.

$width : 500px;

p {
   @if $width < 500px
   {
      background: red;
   }
   @else if $width == 500px
   {
      background: green;
   }
   @else
   {
      background: blue;
   }
}

In the next lesson, Data types in Sass, we'll test our knowledge we have built up so far on some exercises.


 

 

Article has been written for you by Honza Bittner
Avatar
Do you like this article?
1 votes
Everything is possible.
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!