A post about Null Variables in Sass was recently released by Mark Otto.
The gist is: Use null as a value for variables to avoid bloat in CSS output.
This is my take on the topic with small additions.
#Overwriting default variables
// custom config
$module-variable: "custom";
// module config
$module-variable: "default value" !default;
.module {
debug: $module-variable;
}/* CSS OUTPUT */
.module {
debug: "custom";
}By utilizing the !default flag (docs) on the module variable, the value can be overwritten from outside. The declaration will be rendered with either the custom or default value.
#Conditional output and overwrite
By setting null as the default, the declaration will only be rendered when variable gets declared otherwise.
#Overwrite
// custom config
$module-variation: "custom";
// module config
$module-variation: null !default;
.module {
variation: $module-variation;
}/* CSS OUTPUT */
.module {
variation: "custom";
}#Conditional output with null
// module config
$module-variation: null !default;
.module {
variation: $module-variation;
}/* CSS OUTPUT */
.module {
/* no declaration rendered */
}This is helpful when you need conditional declarations without actually using conditions. This makes the code less complex, cluttered and easier to read.
#Conditional output with @if
// module config
$module-variation: null !default;
.module {
// declaration not needed when using `null`
@if ($module-variation) {
variation: $module-variation;
}
}#Faux Overwriting with null
If the variable's default value is declared and overwritten with null, the custom value has no effect and the default value is used.
// custom config
$module-ignore: null;
// module config
$module-ignore: "default" !default;
.module {
ignore: $module-ignore;
}/* CSS OUTPUT */
.module {
ignore: "default";
}#Use conditions for the right purpose
So is this a silverbullet for optional styles? Nah - use the right tool for the job!
If you have multiple declarations or entire rulesets that should be conditionally rendered, use a conditional directive (at-rule) like @if instead.
Example: Modal with an optional backdrop via a pseudo-element.
$modal-backdrop-enable: false !default;
.modal {
// modal styles
...
// backdrop
@if ($modal-backdrop-enable) {
&::after {
...
}
}
}This is a great way to design a flexible module config by giving options, without being too opinionated and bloating the CSS output.
#TLDR
- use
nullas default value to conditionally render declarations - this only works when the default is
null, not if the overwrite isnull - use
@ifwhen conditionally render multiple declarations or entire rulesets