Sass — Variables
Basic variables
$primary: #3498db;
$font-size: 16px;
$border: 1px solid #ccc;
$sidebar-width: 300px;
Color variables
$white: #ffffff;
$black: #000000;
$gray-100: #f8f9fa;
$gray-200: #e9ecef;
$gray-300: #dee2e6;
$gray-600: #6c757d;
$gray-900: #212529;
$primary: $blue-600;
$success: $green-600;
$danger: $red-600;
Variable scopes
$global-var: red;
.nav {
$local-var: blue;
color: $local-var; // works
}
.nav {
color: $local-var; // error - not in scope
}
Default values
$primary: blue !default;
$spacing: 16px !default;
The !default flag only sets the value if it hasn't been defined yet.
Maps
$colors: (
primary: #3498db,
secondary: #2ecc71,
danger: #e74c3c
);
$breakpoints: (
mobile: 480px,
tablet: 768px,
desktop: 1024px
);
Access map values:
.button {
background: map-get($colors, primary);
}
Interpolation
$direction: top;
$amount: 10px;
.margin-top {
margin-#{$direction}: $amount;
}
// Output: .margin-top { margin-top: 10px; }
Multiple properties loop
$properties: margin, padding;
@mixin set-spacing($size) {
@each $prop in $properties {
#{$prop}: $size;
}
}
.box {
@include set-spacing(16px);
}
Dynamic property names
$side: left;
$offset: 20px;
.container {
margin-#{$side}: $offset;
}
Mini Practice
- Create a color palette map
- Build a spacing scale with variables
- Use map-get to build a button system
- Use interpolation for dynamic class names
Up Next
Continue with Nesting — parent selectors and deep nesting.
Related Topics
Frequently Asked Questions about Variables
What is Variables in Sass?
Variables is a fundamental concept in Sass. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Variables?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.
Why is Variables important in Sass?
Variables is essential for Sass development. Understanding this concept will help you write better code and solve real-world problems more effectively.