{SASS: Tutorials}

Lesson 3: Variables

The fun begins. Providing you’ve been through our previous lessons (one and two) you should now have SASS set up on your development machine.

One reason why SASS is worth using over standard CSS is the functionality, and simplicity, of variables. Like a programming language they allow you to set a variable with a value which can be used time upon time – all with a single point to change.

The Basics

A basic variable to hold, for example, the background colour can be declared using the dollar syntax.

$bg: #333;

body {
    background-color: $bg;
}

Output:

body {
    background-color: #333; }

Working with Variables

It’s also possible (and quite useful) to be able to use these variables in conjunction with arithmetic operations. So for example you could make a variable which contains the chosen width of a container div tag. Then use this same variable for two children elements but dividing them in half.

$boxWidth: 600px;
$borderSize: 2px;

.container {
    width: $boxWidth;
    padding: $borderSize * 5;
}

.container div {
    width: $boxWidth / 2;
    border: $borderSize solid gray;
}

Output:

.container {
  width: 600px;
  padding: 10px; }

.container div {
  width: 300px;
  border: 2px solid gray; }

Types

Variables can store nearly any data type imaginable within SASS.

  • Numbers (like 0.1, 10, 100px)
  • Strings (like ‘this’, “that” and tother)
  • Colour (in word form: blue; Hex: #333; RGB: rgb(0, 0, 0);)

So that just about sums up working with variables within SASS. Having problems? Leave us a comment below.

Leave a Reply

Get in Touch



[Coming Soon]

...in the mean time, talk to me on twitter, @eddturtle.