October 7, 2015 8:36 am

Getting Started with Sass Basics Part 1

In the next series of articles, I am going to show you how to work with Sass. Sass is a powerful preprocessor for CSS. It allows you to type CSS in a way similar to programming languages (using variables, loops, functions, lists) which then becomes ordinary CSS that you can use in your projects. Sass saves you time and makes maintenance easier in the long run.


Variables in Sass

Variables in Sass are defined in a way similar to PHP with the difference that you do not use an equals sign (=) but with colons (:).

Here is an example of a variable in Sass:

As you can see the variables can hold hexadecimal color values. They can also hold rgb(a) values.

They can also hold strings, numeric values in whatever unit (such as 16px) and more.

You can later use these variables in place of a property’s value and when Sass compiles to CSS you will have the value stored in the variable in the place where you have used it.

Here is how you can use a string variable in a property:

Nesting selectors

Assume that we have the following markup:

Sass allows us to nest selectors which can facilitate the legibility of the code but it is best to stick with 2 or 3 levels of nesting at most as too much nesting could get hard to maintain and hard to read pretty fast.

With that markup, we define some variables and use them to style our headline. We also use nesting to avoid typing #headline h1 and #headline p all over and increase legibility.

It is important to know that variables in Sass exist in the scope they were defined in. We have defined our variables in a sort of global scope so we would be able to use them anywhere. If we change the variable’s value in a p selector before we set the styles for our headline like this:

Then, the change in the color will be valid only for the scope where it is defined and its children (nested selectors) so the color in the end will be the one defined in the #headline p selector.


To comment your code, you can use the traditional multiline style /* COMMENT HERE */ but you can also use single-line comments like // This comment takes the entire line (like in JavaScript and PHP). If you use single-line comments in Sass then they will be seen only in your Sass files. When you compile the Sass code to CSS your single-line comments would not be present in the produced CSS file.


Before diving into Sass, I encourage you to go to http://sassmeister.com/ where you can find a live environment for writing Sass and HTML and see the result as well as the CSS it compiled into.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter

Tutorial Categories: