Performance: Default values with !default
This affects CSS bundle size and style recalculation speed by controlling variable overrides efficiently.
$primary-color: blue !default; $primary-color: red;
$primary-color: blue; $primary-color: red;
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Reassign variables without !default | N/A | N/A | Larger CSS causes slower style calculation | [X] Bad |
| Use !default for fallback variable values | N/A | N/A | Smaller CSS improves style calculation speed | [OK] Good |
!default flag do when used with a Sass variable?!default!default flag in Sass is used to assign a value to a variable only if it has not been assigned a value before.!default does not perform. It does not make the variable global regardless of scope, force overwrites of previous values, or delete the variable after use.!default means set if unset [OK]blue to a Sass variable $color?$variable-name: value;. To set a default value, add !default after the value.!default. $color: blue !default; correctly uses !default. $color = blue !default; uses an invalid assignment operator =. $color: blue !important; uses !important which is CSS, not Sass variable syntax.$font-size after compilation?$font-size: 16px !default; $font-size: 18px;
$font-size to 16px only if it is not already set. Since it is the first assignment, it sets $font-size to 16px.$font-size to 18px unconditionally, overwriting the previous value.$primary-color: red !default $primary-color: blue;
!default.!default is correct. Variables can be declared globally, not only inside selectors.!default to achieve this?!default flag sets a variable only if it is not already set. To allow user override, the user must set the variable before this file is loaded.$button-color first without !default, then tries to set default, which won't work as intended. $button-color: blue !default;
$button-color: green; sets default first, then overwrites it, so user cannot override easily. $button-color: blue !default; sets default but does not mention user override. $button-color: blue !default;
// User sets $button-color: green before importing this file correctly shows default with comment explaining user sets variable before import, enabling override.Pass the test and this pattern moves unknown