How to Work with Default Variable Values in Scss

Feature thumb course thumb

We've walked through how to work with variables in Scss to make it possible to make a single change that populates a number of style definitions. To take this knowledge a step further, in this guide we'll examine how to set default variable values in Scss.

This may not seem like a big topic to learn because it's mainly important in situations where you are white labeling styles in an application. However, I think it can be a helpful skill to understand and it also is a good introduction to learning about how Scss manages variable scope.

Variable scope is the process that programming languages use to control where variables can be accessed throughout a program.

Example of Using Variables in Scss

For this example, let's imagine a scenario where you are building a set of styles that are going to be utilized on multiple websites. Services such as Wix and Squarespace have to implement this type of behavior throughout their entire systems. For our example, we want our color scheme to have a dark red set of colors for heading text and section backgrounds.

We'll implement Scss mixins and add variables with the !default flag on them. If you're not familiar with mixins, we'll dive into them later on, for right now just think of them like reusable code snippets that can be called. You can see the results below:

See the Pen Scss Course by Jordan Hudgens (@jordanhudgens) on CodePen.

Don't worry about understanding all of the code if it looks different than you're used to. Simply focus on seeing how we're setting the default colors in each of the mixins, which results in the dark red color that we're looking for.

Making the Variables Dynamic with the !default Flag

Now, let's imagine that we have two clients come along. The first client likes the red color, so we don't have to make any changes. However, the second client wants to have a dark cyan color for their application. If we didn't use the !default flag, we'd have to go throughout the entire application and change all of the values. Additionally, if the application is dynamic we'd need to figure out a way to perform an override on the value, such as using inline styles, which can be buggy and breaks a number of best practices.

However, because we used the !default flag in our mixins, we can simply add a single line at the top of the file that will be viewed as the new 'master' color. Because the other color variables have the !default flag, Scss will ignore those variable declarations and will only use the new one that's provided. The final code and result can be found in this codepen.

And that's how to implement the !default flag with Scss variables. I've also included links to a few other resources that you can use to broaden your knowledge on the topic.