Image for post
Image for post
Photo by Roman Mager on Unsplash

Handling SCSS variables at scale

David Berner
Sep 3, 2017 · 2 min read

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:

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:

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.

FED || Dead

A bunch of passionate frontend devs writing & speaking…

David Berner

Written by

Principal Frontend Developer at Avocado Consulting

FED || Dead

A bunch of passionate frontend devs writing & speaking about their adventures in frontend land.

David Berner

Written by

Principal Frontend Developer at Avocado Consulting

FED || Dead

A bunch of passionate frontend devs writing & speaking about their adventures in frontend land.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store