Codeskill

Learn to code, step by step

Variables in SCSS: Dynamic Styling Made Easy

A look at SCSS variables: how to declare them, use them, and keep your stylesheets easier to maintain.

Why use variables?

If you have ever updated the same colour or font size across a dozen CSS selectors, you know the problem variables solve. They store a value once – colours, font stacks, spacing, anything – and let you reuse it throughout your stylesheet. Change the variable, and every reference updates.

Declaring variables

Variables start with a dollar sign ($), followed by the name:

$primary-color: #3498db;
$secondary-color: #2ecc71;
$font-stack: Helvetica, sans-serif;
$base-font-size: 16px;

Four variables – two colours, a font stack, and a base font size.

Using variables

Once declared, reference them anywhere in your stylesheet:

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

a {
  color: $secondary-color;
  &:hover {
    color: darken($secondary-color, 10%);
  }
}

Notice how the hover state combines a variable with the darken function – that is a common pattern in SCSS.

Advantages of using variables

  1. Maintainability: change a value once and it updates everywhere. Handy for theme colours, typography, and spacing.
  2. Readability: $primary-color is clearer than a hex code scattered through your CSS.
  3. Flexibility: variables work with functions and mixins for more dynamic styling.

Advanced variable usage

Default variables

Use !default to assign a fallback value. Useful when building themes or libraries:

$primary-color: #3498db !default;

$primary-color will be #3498db unless it has already been set elsewhere.

Scope of variables

Variables declared outside any selector are global. Variables declared inside a selector are local to that block:

$global-color: #333;

.container {
  $local-color: #777;
  color: $local-color;
}

// This will cause an error
// color: $local-color;

$global-color is available everywhere. $local-color only exists inside .container.

Using variables with other SCSS features

Variables work well with mixins. You can pass them as arguments:

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

.box {
  @include border-radius(10px);
}

Here, $radius is a variable used inside the mixin to set the border-radius.

Tips for using variables

  1. Naming convention: use clear, descriptive names.
  2. Organising variables: keep them together, ideally in a separate partial like _variables.scss.
  3. Variable types: variables can hold more than strings and numbers – selectors, properties, even media queries.

Variables are one of the first SCSS features worth adopting. Get into the habit of defining colours and sizes as variables early, and you will save yourself a lot of find-and-replace later.

PreviousSCSS Syntax Deep Dive: Understanding the Basics