Variables

Store reusable values in variables that start with a dollar sign.

Syntax$variable-name: value;

A Sass variable stores a value you can reuse. Variable names start with a dollar sign $.

Define a variable once, then reference it anywhere. Change it in one place and every use updates when you recompile. This is perfect for brand colors, spacing scales, and font stacks.

Scope

A variable declared at the top level of a file is global. One declared inside a rule or block is local to that block. Use the !global flag to assign a global variable from inside a block.

Example

Example · css
$primary: #CC6699;
$spacing: 16px;
$font-stack: 'Helvetica Neue', Arial, sans-serif;

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

/* Compiles to:
body {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #CC6699;
  padding: 16px;
}
*/

When to use it

  • A UI developer stores all brand colors in Sass variables at the top of a tokens file so changing the primary color propagates across every component automatically.
  • A team keeps font sizes, border radii, and z-index levels in variables to enforce a consistent visual language without magic numbers scattered through the codebase.
  • A developer renames a variable from $blue to $primary-action and all usages update in one find-and-replace, keeping the stylesheet semantically meaningful.

More examples

Declaring and using variables

Three Sass variables capture design decisions once; the .btn rule references them all, making future changes a one-line update.

Example · css
$primary:   #2563eb;
$font-base: 1rem;
$radius:    4px;

.btn {
  background:    $primary;
  font-size:     $font-base;
  border-radius: $radius;
}

Variables for spacing scale

A named spacing scale built from variables removes all magic pixel values and enforces a consistent 4px grid.

Example · css
$space-1:  4px;
$space-2:  8px;
$space-4: 16px;
$space-8: 32px;

.card {
  padding: $space-4;
  margin-bottom: $space-8;
  gap: $space-2;
}

Scoping variables locally

Demonstrates that a variable declared inside a selector is scoped to that block and does not affect the global value.

Example · css
$color: #333; // global

.sidebar {
  $color: #555; // local override
  color: $color; // uses #555
}

.main {
  color: $color; // still uses #333
}

Discussion

  • Be the first to comment on this lesson.