Photo by Roman Mager on Unsplash

Handling SCSS variables at scale

Variables in SCSS are a wonderful thing but they can quickly get out of hand, trying to maintain them across several files without accidentally reassigning them or keeping track of where they originated or what their scope is supposed to be.

The problem fundamentally is that SCSS has no concept of locally scoped variables, much like CSS itself, everything is in the global namespace.

I’ve adopted a pattern that I’ve used in my projects for the last couple of years where scoping is emulated using a simple naming convention.

I have a single _variables.scss file which contains all my “global” variables. These are all prefixed g- to easily identify them across the app.

For example:

// _variables.scss
// Colours
$g-color-blue: #509cf6;
$g-color-green: #1bb362;
$g-color-brand: $g-color-green;

// Font scale
$g-font-size: 16;
$g-font-size-large: 20;

The g- flag indicates they are intended to be used across multiple files.

Then in my component files I have a set of variables declared at the top of the file. For example if I had an accordion component I would set out the file along the following lines:

// _accordion.scss
// Variables
$c-accordion-background-color: $g-color-blue;
$c-accordion-font-size: $g-font-size-large;

// Base
.c-accordion { 
background-color: $accordion-background-color;
font-size: rem($g-font-size-large);

This is obviously a contrived example, but I have found this pattern to be hugely beneficial on huge projects with large numbers of components and app-wide variables to keep track of.

It is important to note that local component / module variables should exclusively be used in their component files in order to emulate local scope.

Like what you read? Give David Berner a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.