Go to main content
, Johan Ronsse

Using null in SCSS variables to avoid unnecessary output

Here’s a little CSS trick that can help with skinnable/themeable websites. Let’s say you’re creating a button whose theme is overridable. You would use !default to define a default background color, and then define SCSS that comes in front of this rule to override the default variable:

// Theme
$button-bg: green;

// Base code
$button-bg: blue !default;

.button {
  background: $button-bg;
}

This would output:

.button {
  background: green;
}

Now, what if you have a variable that’s not always needed? Like, let’s say a border radius that might exist, but also might not? You can use null as a value. When you use code like this:

// Theme
$button-bg: green;
$button-border-radius: 3px;

// Base code
$button-bg: blue !default;
$button-border-radius: null !default; // <-- Trick here!

.button {
  background: $button-bg;
  border-radius: $button-border-radius;
}

The output will be:

.button {
  background: green;
  border-radius: 3px;
}

But let’s say your theme has no rounded corners, and you simply don’t define the $border-radius variable in your theme, the output will simply be:

.button {
  background: green;
}

Thanks to Brad Frost for pointing this out.

Johan Ronsse

About the author:

Johan Ronsse is an interface designer who is trying to find the balance between aesthetics and usability. He tweets as @wolfr_2.

Leave a comment

Your email address will not be published. Required fields are marked *