Developer Tools

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: