Null variables in Sass
Bootstrap is a large and complex frontend library with some powerful functionality and customization built-in. Occasionally though, we get asked to make things even more customizable for folks with more CSS properties and default variables.
This is largely because Bootstrap’s CSS relies on some limited global inheritance of general styles (font
, color
, line-height
, and more), but developers and designers often want to customize things further. So we were typically faced with adding CSS we didn’t need at the outset, and that you might need. This just didn’t seem right for any of us.
Back in January, thanks to one of our maintainers Martijn, we started using null
value default variables to combat that bloat while still increasing our level of customization.
Here’s a basic example:
$body-text-align: null !default;
body {
text-align: $body-text-align; // Won’t compile
}
As you can see, the Sass compiler will ignore the entire property: value;
declaration because the value is null
. But, if someone customized this before compilation by overriding that default value, the CSS would compile. Here’s an example of how you’d override that default variable.
// First, override `!default` variables
$body-text-align: left;
// Second, import Bootstrap
@import “bootstrap”;
And here’s how it compiles to CSS.
body {
text-align: left;
}
It’s also worth mentioning that these null
values can be used in mixins, too. Check out this old Treehouse article for details.
Historically, more flexibility in our default styles meant more code for everyone, but with null
value default variables, we can continue to provide more customization when warranted without knowingly adding bloat to our compiled CSS. I still owe Bootstrap a fresh pass at this to see what we can remove.
Hopefully we can continue to find more techniques for increased customization and smaller file sizes. Please share if you have them!