0
0
SASSmarkup~15 mins

Variable declaration with $ in SASS - Deep Dive

Choose your learning style9 modes available
Overview - Variable declaration with $
What is it?
In Sass, variables are declared using the $ symbol followed by a name and a value. These variables store values like colors, sizes, or fonts that you want to reuse throughout your stylesheets. Using variables helps keep your styles consistent and easy to update. Instead of repeating the same value many times, you just change it once in the variable.
Why it matters
Without variables, you would have to write the same colors or sizes over and over in your CSS. This makes it hard to update your design because you must find and change every instance manually. Variables save time and reduce mistakes by letting you change a value in one place and have it update everywhere. This makes your stylesheets cleaner and easier to maintain.
Where it fits
Before learning Sass variables, you should understand basic CSS syntax and how styles apply to HTML elements. After mastering variables, you can learn about Sass features like nesting, mixins, and functions, which build on variables to create powerful, reusable styles.
Mental Model
Core Idea
A Sass variable is like a labeled container that holds a style value you can reuse and change easily throughout your stylesheet.
Think of it like...
Imagine a kitchen where you label jars with spices like 'salt' or 'pepper'. Instead of writing 'salt' every time you cook, you just grab the jar labeled 'salt'. If you want to change the salt brand, you only change the jar's content, not every recipe.
┌───────────────┐
│ $primary-color│───┐
│ value: #3498db │   │
└───────────────┘   │
                    ▼
          ┌─────────────────────┐
          │ .button {           │
          │   background: $primary-color; │
          │ }                   │
          └─────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is a Sass variable?
🤔
Concept: Introducing the basic idea of variables in Sass using the $ symbol.
In Sass, you create a variable by writing a $ followed by a name and a value. For example: $main-color: #ff0000; This means $main-color now holds the color red. You can use this variable anywhere in your Sass code instead of writing #ff0000 again.
Result
You have a named value stored that you can reuse in your styles.
Understanding that variables store values lets you avoid repeating the same information, making your code cleaner and easier to change.
2
FoundationUsing variables in styles
🤔
Concept: How to apply variables inside CSS properties.
Once you declare a variable, you can use it in your CSS rules. For example: $font-size: 16px; body { font-size: $font-size; } This sets the font size of the body to 16 pixels using the variable.
Result
The CSS output will have font-size: 16px; applied to the body element.
Using variables in properties connects the stored value to actual styles, showing how variables control the look of your page.
3
IntermediateChanging variables updates styles
🤔Before reading on: If you change a variable's value, do you think all uses of that variable update automatically or only new uses?
Concept: Variables are dynamic references that update all styles using them when changed.
If you change the value of a variable, every place that uses it will reflect the new value. For example: $bg-color: white; header { background-color: $bg-color; } Later, if you change $bg-color to black, the header's background color changes to black everywhere.
Result
All styles using $bg-color update to the new value automatically.
Knowing variables act like references helps you understand how one change can affect many styles, saving time and preventing errors.
4
IntermediateVariable scope in Sass files
🤔Before reading on: Do you think variables declared inside a block are available everywhere or only in that block?
Concept: Variables have scope, meaning where they can be used depends on where they are declared.
Variables declared at the top level of a Sass file are global and can be used anywhere. Variables declared inside a selector or block are local to that block. For example: $color: blue; // global .container { $color: red; // local color: $color; // uses red } p { color: $color; // uses blue }
Result
The container text is red, but paragraphs outside use blue.
Understanding scope prevents confusion about which variable value is used and helps organize styles better.
5
IntermediateDefault values with !default
🤔Before reading on: If a variable is already set, does !default overwrite it or keep the original value?
Concept: The !default flag sets a variable only if it hasn't been set before.
You can write: $primary-color: blue !default; This means if $primary-color is not set yet, it becomes blue. But if it was set earlier, this line does nothing. This helps when you want to provide fallback values without overwriting user settings.
Result
Variables keep their first assigned value unless unset, making styles flexible.
Knowing !default helps you write reusable code that adapts to different projects without breaking existing variables.
6
AdvancedVariables in partials and imports
🤔Before reading on: Do variables declared in imported files become available in the main file automatically or not?
Concept: Variables declared in imported Sass files (partials) become available in the importing file, enabling modular styles.
Sass lets you split styles into multiple files called partials, which start with an underscore, like _colors.scss. You can declare variables there: // _colors.scss $brand-color: #123456; Then import it: @import 'colors'; body { color: $brand-color; } This way, variables are shared across files.
Result
The main stylesheet uses variables from imported partials, keeping code organized.
Understanding how variables work across files helps build scalable, maintainable projects.
7
ExpertVariable interpolation and dynamic names
🤔Before reading on: Can you use variables to create other variable names dynamically in Sass, or is that impossible?
Concept: Sass allows variable names to be built dynamically using interpolation, enabling advanced patterns.
You can create variable names using interpolation like this: $side: left; $margin-left: 10px; $property: margin-#{$side}; .element { #{$property}: 10px; } This outputs: .element { margin-left: 10px; } This technique helps when you want to generate styles programmatically.
Result
You can write flexible styles that adapt based on variable values.
Knowing variable interpolation unlocks powerful dynamic styling techniques rarely used by beginners.
Under the Hood
When Sass processes your files, it reads variable declarations and stores their values in a map-like structure. Each time it encounters a variable reference, it looks up the current value in this map. During compilation, Sass replaces variables with their stored values to produce plain CSS. Variable scope is managed by tracking where variables are declared and limiting their visibility accordingly.
Why designed this way?
Sass was designed to extend CSS with programming features like variables to reduce repetition and improve maintainability. The $ syntax was chosen to clearly distinguish variables from CSS properties. The scope rules and !default flag provide flexibility for modular code and safe defaults, reflecting common needs in large projects.
┌───────────────┐
│ Sass File     │
│ $var: value;  │
│ ...           │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Sass Compiler │
│ Stores vars   │
│ Resolves refs │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Output CSS    │
│ property: value;│
│ ...           │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does changing a variable after using it in a style update that style automatically? Commit yes or no.
Common Belief:Once a variable is used in a style, changing it later won't affect that style.
Tap to reveal reality
Reality:Variables are replaced during compilation, so changing a variable's value before compiling updates all uses everywhere.
Why it matters:Believing otherwise can cause confusion when styles don't update as expected, leading to wasted debugging time.
Quick: Are Sass variables the same as CSS custom properties (variables)? Commit yes or no.
Common Belief:Sass variables and CSS variables are the same and work the same way in the browser.
Tap to reveal reality
Reality:Sass variables exist only during compilation and are replaced with static values; CSS variables exist in the browser and can change dynamically.
Why it matters:Confusing these leads to wrong assumptions about runtime behavior and limits of Sass variables.
Quick: If you declare a variable inside a selector, is it available globally? Commit yes or no.
Common Belief:Variables declared anywhere are always global and accessible everywhere.
Tap to reveal reality
Reality:Variables declared inside selectors are local to that block and not accessible outside.
Why it matters:Misunderstanding scope causes bugs where variables seem missing or have unexpected values.
Quick: Does the !default flag overwrite existing variable values? Commit yes or no.
Common Belief:!default always sets the variable value no matter what.
Tap to reveal reality
Reality:!default only sets the variable if it is not already set.
Why it matters:Misusing !default can overwrite important values or prevent intended overrides.
Expert Zone
1
Variables declared with !default allow libraries to provide safe defaults without overwriting user customizations, enabling flexible theming.
2
Variable scope can be tricky when using nested selectors or imports; understanding how Sass merges scopes prevents subtle bugs.
3
Variable interpolation can be combined with maps and loops to generate complex, dynamic stylesheets programmatically.
When NOT to use
Avoid using Sass variables when you need runtime dynamic changes, such as user-controlled themes, where CSS custom properties are better. Also, for very simple stylesheets, variables might add unnecessary complexity.
Production Patterns
In production, variables are often organized in separate partial files for colors, typography, and spacing. Teams use !default to allow easy overrides. Variables combined with mixins and functions create design systems that scale across large projects.
Connections
CSS Custom Properties
Related but different; Sass variables compile to static values, CSS variables exist at runtime.
Knowing the difference helps choose the right tool for dynamic theming versus compile-time consistency.
Programming Variables
Sass variables behave like variables in programming languages, storing values for reuse.
Understanding programming variables clarifies how Sass variables hold and replace values during compilation.
Database Configuration Settings
Both store reusable values that control behavior or appearance, allowing centralized updates.
Seeing variables as configuration helps appreciate their role in managing complexity and consistency.
Common Pitfalls
#1Using variables before declaring them causes errors.
Wrong approach:body { color: $text-color; } $text-color: #333;
Correct approach:$text-color: #333; body { color: $text-color; }
Root cause:Sass processes files top to bottom; variables must be declared before use.
#2Assuming variables declared inside selectors are global.
Wrong approach:.container { $color: red; } p { color: $color; }
Correct approach:$color: red; .container { color: $color; } p { color: $color; }
Root cause:Variables inside blocks are local; misunderstanding scope causes missing variable errors.
#3Overwriting variables unintentionally by missing !default usage.
Wrong approach:$primary-color: blue; $primary-color: red;
Correct approach:$primary-color: blue !default; $primary-color: red;
Root cause:Without !default, later declarations overwrite earlier ones, breaking intended defaults.
Key Takeaways
Sass variables declared with $ store reusable style values that simplify and unify your CSS.
Variables must be declared before use and have scope rules that affect where they work.
Changing a variable updates all styles using it, making global design changes easy.
The !default flag lets you set fallback values without overwriting existing ones.
Understanding the difference between Sass variables and CSS custom properties is key for choosing the right tool.