0
0
SASSmarkup~3 mins

Variable scope (global vs local) in SASS - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how controlling where your colors and sizes apply can save hours of frustrating bugs!

The Scenario

Imagine you are writing styles for a website and you create a color variable at the top. Then inside a button style, you create another variable with the same name but a different color.

You want to use the button color inside the button only, but accidentally the whole site changes color because you didn't control where the variable applies.

The Problem

Without understanding variable scope, you might overwrite colors everywhere or get unexpected results. You have to rename variables all the time or guess which color is used where. This makes your styles confusing and hard to fix.

The Solution

Variable scope in Sass lets you decide if a variable is global (used everywhere) or local (used only inside a block). This way, you can safely reuse variable names without conflicts and keep your styles organized.

Before vs After
Before
$color: blue;
.button {
  $color: red !global;
  color: $color;
}
body {
  color: $color;
}
After
$color: blue !global;
.button {
  $color: red;
  color: $color;
}
body {
  color: $color;
}
What It Enables

You can write clean, reusable styles where variables only affect the parts you want, avoiding accidental changes and confusion.

Real Life Example

When styling a website, you might have a global primary color but want a special button to use a different shade without changing the whole site's color scheme.

Key Takeaways

Variable scope controls where variables apply in your styles.

Global variables affect the whole stylesheet; local variables only affect inside blocks.

Using scope prevents accidental overwrites and keeps code clear.