(click anywhere to close)

[SASS] Variables

category: Website | course: SASS | difficulty:
1. Variables in Selecto...

Perhaps the greatest advantage of using SASS, is being able to use variables. Instead of copying or retyping similar or exactly the same bits of code, we can save it inside a variable name once, and use that. To declare a variable, use the following dollar syntax:

$some-variable-name: value;

A variable can be one of six different types:

  • String: Any piece of text. Usually enclosed within quotes, but not necessary.
  • Number: Any number (with and without unit).
  • Colour: Any colour.
  • Boolean: Either true or false.
  • List: A list of properties of varying types. This can be a spaced list, or one with commas.
  • Maps: A mapping of values to other values.
  • Null
$a-cool-string: "Juan is a cool guy";
$a-number: 350;
$some-colour: #FFAA22;
$boolean: true;
$a-fancy-list: 5px solid grey;
$an-intricate-map: (text: green, header: red, remark: grey);
$null-variable: null;

As you can see, maps are created with a syntax that is quite peculiar for CSS. The general form is (key1: value1, key2: value2, …). Nevertheless, maps can be extremely useful sometimes.

When you use a variable, it just inserts the literal value of that variable into the CSS code. This makes it very easy and intuitive to use, and allows for great flexibility. I suggest you put anything that is likely to be used more than once inside a variable.

I also suggest giving the variables descriptive names, and working with scales. For example, $font-stack-body and $font-stack-headers, is better than $font-stack-one and $font-stack-two

The naming convention is to place dashes between words, just as regular CSS does with its properties. This is, however, not necessary if you prefer your own methods.

Variables in Selectors

Variables are typically used to insert a value somewhere, but we can also use them in selectors or property names. To do so, we need to wrap the variable name inside the interpolation syntax. Sounds difficult, but it simply looks like

p.#{someclassname} {
	font-size: $paragraph-size;
	color: $paragraph-colour;
Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk