Change SCSS variables from other files

My ultimate goal is to make one template file which i can modify for different pages. My approach was to create a template.scss and a modifier.scss

in template.scss I set

$background: green; 
background: $background  

in modifier.scss I set

@import 'template';
$background: red;

and expect the background to change, however nothing happens.
obviously this is the wrong approach, how should i do it?

Upvotes: 3

Views: 2724

Answers (3)

FelipeAls
FelipeAls

Reputation: 22161

You can make that variable a !default in your template.scss and import latter file in a different order in modifier.scss.

Variable Defaults: !default (Sass reference)

In template.scss

$background: green !default; 
background: $background;  

and then in modifier.scss

$background: red;
@import 'template';

green shouldn't be assigned to the variable if it was already set to red, which is the case in modifier.scss (edit: s/won't/shouldn't I didn't test it yet with partials)

Upvotes: 1

Maxime Gélinas
Maxime Gélinas

Reputation: 2330

Using this way

variables-template.css (contains variables only)

$background: green;

variables-modifier.css (contains variables only)

$background: red;

styles-template.css (contains your styles)

body { background-color: $background; }

main.css (contains your importation logic)

@import 'variables-template.css';
@import 'variables-modifier.css';
@import 'styles-template.css';

Bonus: Using the Strawberry framework

Strawberry has been created for this kind of situation!

See StrawberrySass.

Upvotes: 0

Brett DeWoody
Brett DeWoody

Reputation: 62773

You are correct in that this approach won't work. Think about how those files would be interpreted.

Example

template.scss

$background:   green; 
background: $background 

modifier.scss

@import 'template';
$background: red;

In this case you're essentially doing:

$background: green; 
background: $background
$background: red; 

The end effect is background is set to green, and the $background variable is redefined to red in the end.

You would need to define background: $background again within modifier.scss in order for you current setup to work.

A Different Approach

One approach is to define your base styles within one file, modifier styles within another, and then set your CSS properties within a final file. Like this:

template.scss

$background: green; 

modifier.scss

$background: red;

styles.scss

background: $background;

Upvotes: 3

Related Questions