- Southampton, England
Using Guarded Assignment or !default
in Sass
How does Sass's guarded assignment (!default
) keyword work?
/ defaults / $module_height: 20px !default; $module_bgcolor: #ccc !default;
.module { height: $module_height; / height: 18px; / background: $module_bgcolor; / background: #ccc; / }
!default
will assign a value only if the variable doesn't already have one. In other words, it prevents a variable from being reassigned.
How is this useful? It allow us to create customisable modules with fallbacks. Let's say we've created a headings module that styles the page headers:
h2 { font-size: 1.5em; color: #333; }
That's fine but it's not not customisable. Here's where we introduce guarded assignment. Developers using the module can now customise the headers as they choose.
Here's the updated headers module:
h1 { font-size: $h1_font_size; color: $h1_color; }
h2 { font-size: $h2_font_size; color: $h2_color; }
Consuming and customising the module is now a trivial task. Note here the order of things. The variables are defined before importing the headers module:
@import "headers"
Here's the final css output.
h1 { font-size: 36px; color: #222 }
h2 { font-size: 1.5em; color: red; }