Can SASS automatically reuse colour variables across multiple components?

Viewed 126

In my project I have a series of colours which are reused in several places around the site and set as variables. In the HTML they are a class on the element.

I have SASS files for each component, so I end up with multiple places in my code where I have to list out the different colour variations. When I add a new colour option, I need to also add a block fo the new colour to multiple components.

Is there a way to automate this, so that just by adding a new colour variable, a new block is created in each of the components? So it will just work without having to create a new variation to every component each time?

variables.scss

$red = #f00;
$blue = #0f0;
$green = #f00;

charts.scss

.chart {
    &.red { border: 6px solid $red; }
    &.green { border: 6px solid $green; }
    &.blue { border: 6px solid $blue; }
}

section.scss

.section {
    &.red { background-color: $red; }
    &.green { background-color: $green; }
    &.blue { background-color: $blue; }
}

image.scss

.image {
    &.red { color: $red; }
    &.green { color: $green; }
    &.blue { color: $blue; }
}

panel.scss

.panel {
    &.red { border-bottom: 5px solid $red; }
    &.green { border-bottom: 5px solid $green; }
    &.blue { border-bottom: 5px solid $blue; }
}

Thanks!

2 Answers

In your variables.css you can add

@import 'charts';
@import 'section';
@import 'image';
@import 'panel';

The @import rule is being phased out of Sass, in its place use the @use instead.

I'd rename the variables.scss to settings.scss and place the colors in that file as they are not variable and are a global setting.

There should be an overall file that compiles all your Sass into one, usually called Application.scss or styles.scss but you can call it whatever you like. List all the files you would like to compile in this file.

So Applications.sccs would look like:

@use 'settings';
@use 'charts';
@use 'section';
@use 'image';
@use 'panel'; 

Make sure settings that has the colors is listed at the top to ensure the cascade of code into the flow of files.

Related