SCSS by Example: Variables
Storing reusable values throughout stylesheets with this sample code demonstrating variable declaration using dollar sign syntax, global and local scope rules, and how variables compile away into regular CSS values.
Code
// Define variables using $
$primary-color: #3498db;
$font-stack: 'Helvetica Neue', sans-serif;
$base-padding: 16px;
body {
font-family: $font-stack;
color: $primary-color;
padding: $base-padding;
}
// Variables can be scoped
.container {
$local-color: #e74c3c;
background-color: $local-color;
// $local-color is not available outside .container
}Explanation
Variables in SCSS are declared using the dollar sign $ prefix and can store any CSS value including colors, font stacks, numbers, strings, booleans, lists, and maps. When the SCSS is compiled, variables are replaced with their actual values in the final CSS output. Unlike CSS custom properties which remain in the compiled CSS and can be manipulated at runtime, SCSS variables are compile-time only and completely disappear from the final stylesheet.
SCSS variables follow lexical scoping rules where variables defined at the top level are global and accessible anywhere in the stylesheet, while variables defined inside a selector block are local to that block and its nested children. This scoping prevents naming conflicts in large projects where different components might use similar variable names. Variables can be shadowed by defining a local variable with the same name as a global one, and the local version takes precedence within its scope.
The compilation process resolves all variable references to their concrete values, which means changing a variable value in one place automatically updates all references throughout the stylesheet. This makes SCSS variables particularly valuable for maintaining design consistency across large codebases, as design tokens like brand colors, spacing scales, and typography can be centralized and modified from a single source of truth.
Code Breakdown
$primary-color: ... declares a global variable using dollar sign prefix.color: $primary-color; references variable, compiles to color: #3498db;.$local-color is scoped to .container block and inaccessible outside.
