SyntaxStudy
Sign Up
SASS / SCSS Variable Scope and the !default Flag
SASS / SCSS Beginner 1 min read

Variable Scope and the !default Flag

SASS variables follow lexical scoping rules. A variable declared at the top level of a file is globally accessible to all code in that file and any files that import it. A variable declared inside a selector, mixin, or function block is local to that block and cannot be accessed from outside. If a local variable shares a name with a global variable, the local one takes precedence within its block. The `!default` flag is a powerful tool for building configurable libraries. When you write `$variable: value !default`, SASS only assigns that value if the variable has not already been assigned. This lets consumers of your library override defaults simply by declaring the variable before importing the library partial. The `!global` flag has the opposite purpose: it forces a local assignment to update the global variable of the same name. While this is occasionally useful, it should be used sparingly because it makes code harder to reason about. In modern SASS using `@use`, module configuration via `with ()` is the preferred way to customise library variables.
Example
// ── Variable scope demonstration ──────────────────────────────────────────────

// Global variable
$theme-color: #3498db;

.component {
    // Local variable — only lives inside this block
    $padding: 1rem;
    padding: $padding;
    color  : $theme-color;  // global is accessible here

    .inner {
        // $padding is still in scope because inner is nested inside .component
        margin: $padding / 2;
    }
}

// $padding is NOT accessible here — it was local to .component

// ── !default flag for configurable partials ───────────────────────────────────

// _theme.scss  (library partial)
$primary    : #3498db !default;  // used only if $primary not already set
$secondary  : #2ecc71 !default;
$base-font  : 'Inter', sans-serif !default;

.btn-primary {
    background: $primary;
    font-family: $base-font;
}

// main.scss  (consumer overrides BEFORE importing)
$primary   : #8e44ad;  // overrides the !default value
$base-font : 'Georgia', serif;

@use 'theme';  // now uses purple + Georgia instead of the defaults

// ── !global flag (use sparingly) ─────────────────────────────────────────────
$counter: 0;

@mixin increment {
    $counter: $counter + 1 !global;  // modifies the global $counter
}