Codeskill

Learn to code, step by step

Embracing Variables in SASS: A Game-Changer for Stylesheets

SASS variables – one of the most useful features in the language. If you have repeated the same colour hex code or font stack across a stylesheet, variables are the fix.

What are SASS variables?

In plain CSS, you often repeat values – colours, font sizes, margins, and so on. Changing one means hunting through the file and hoping you did not miss a copy. SASS variables let you store a value once and reuse it everywhere. Update the variable and every reference updates with it.

The basics of SASS variables

A SASS variable starts with a dollar sign $. Here is a simple example:

$primary-color: #3498db;
$font-stack: Helvetica, sans-serif;

We have defined a colour and a font stack. Instead of repeating the hex code or font names, we use these variables wherever we need them.

Implementing variables in your styles

Using variables is straightforward:

body {
  font-family: $font-stack;
  color: $primary-color;
}

When compiled, that becomes:

body {
  font-family: Helvetica, sans-serif;
  color: #3498db;
}

Advantages of using SASS variables

  1. Maintainability: Change the variable once and it updates everywhere. Particularly useful on large projects or when handing work to someone else.
  2. Readability: Meaningful names like $primary-color are easier to scan than raw hex codes.
  3. Flexibility: Experiment with different values without a find-and-replace hunt.

Advanced usage

Variables are not limited to colours and fonts. You can use them for almost any CSS value. For consistent spacing across a layout:

$base-spacing: 15px;

.content {
  padding: $base-spacing;
}

.sidebar {
  margin: $base-spacing;
}

You can also perform operations on variables:

$base-spacing: 15px;

.content {
  padding: $base-spacing * 2;
}

That sets the padding to 30px – twice the base spacing.

Dynamic variables with !default

SASS provides the !default flag for variables. It sets a default value only if the variable is not already assigned – handy in themes or shared libraries:

$theme-color: blue !default;

.body {
  background: $theme-color;
}

If $theme-color is not already set, it defaults to blue.

Variables are one of the first SASS features worth adopting. They cut repetition, make global changes simple, and cost almost nothing to learn.

PreviousThe Stylish Advantages of SASS over Traditional CSS