Sass !default and themeable design systems

Programming - Mar 31, 2024

This is a great blog post from Brad Frost where he walks us through an interesting example. Let’s say we’re making a theme and we have some Sass like this:

.c-text-input {
  background-color: $form-background-color;
  padding: 10px
}

If the $form-background-color variable isn’t defined then we don’t want the background-color to be outputted in our CSS at all. In fact, we want our output to look like this instead:

.c-text-input {
  padding: 10px;
}

See? No background-color property. As Brad shows, that’s possible today with Sass’s !default flag. You can use it like this as you’re setting up the variable:

$form-background-color: null !default;

.c-text-input {
  background-color: $form-background-color; /* this line won’t exist in the outputted CSS file */
  padding: 10px;
}

$form-background-color: red;

.c-text-input-fancy {
  background-color: $form-background-color; /* this line will be “red” because we defined the variable */
  padding: 10px;
}

It’s a really useful thing to remember if you want to ensure your CSS is as small as it can be while you’re creating complex themes with Sass.

Direct Link →

Previous Next
Copyrights
We respect the property rights of others, and are always careful not to infringe on their rights, so authors and publishing houses have the right to demand that an article or book download link be removed from the site. If you find an article or book of yours and do not agree to the posting of a download link, or you have a suggestion or complaint, write to us through the Contact Us .
Read More