Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS - use variables across multiple files

Tags:

css

sass

I would like to keep one central .scss file that stores all SASS variable definitions for a project.

// _master.scss   $accent: #6D87A7;            $error: #811702; $warning: #F9E055; $valid: #038144; // etc...  

The project will have a large number of CSS files, due to its nature. It is important that I declare all project-wide style variables in one location.

Is there a way to do this in SCSS?

like image 849
dthree Avatar asked Jul 11 '13 16:07

dthree


People also ask

How do you access a variable in Sass?

The basic syntax for defining a variable is simple: Just use a $ before the variable name and treat its definition like a CSS rule: Sass Variable Syntax: $<variable name>:<value>; The following declares a variable named large-font.

Is Sass and SCSS same?

SASS (Syntactically Awesome Style Sheets) is a pre-processor scripting language that will be compiled or interpreted into CSS. SassScript is itself a scripting language whereas SCSS is the main syntax for the SASS which builds on top of the existing CSS syntax.


2 Answers

You can do it like this:

I have a folder named utilities and inside that I have a file named _variables.scss

in that file i declare variables like so:

$black: #000; $white: #fff; 

then I have the style.scss file in which i import all of my other scss files like this:

// Utilities @import "utilities/variables";  // Base Rules @import "base/normalize"; @import "base/global"; 

then, within any of the files I have imported, I should be able to access the variables I have declared.

Just make sure you import the variable file before any of the others you would like to use it in.

like image 82
Joel Avatar answered Oct 05 '22 11:10

Joel


This question was asked a long time ago so I thought I'd post an updated answer.

You should now avoid using @import. Taken from the docs:

Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely. Prefer the @use rule instead.

A full list of reasons can be found here

You should now use @use as shown below:

_variables.scss

$text-colour: #262626; 

_otherFile.scss

@use 'variables'; // Path to _variables.scss Notice how we don't include the underscore or file extension  body {   // namespace.$variable-name   // namespace is just the last component of its URL without a file extension   color: variables.$text-colour; } 

You can also create an alias for the namespace:

_otherFile.scss

@use 'variables' as v;  body {   // alias.$variable-name   color: v.$text-colour; } 

EDIT As pointed out by @und3rdg at the time of writing (November 2020) @use is currently only available for Dart Sass and not LibSass (now deprecated) or Ruby Sass. See https://sass-lang.com/documentation/at-rules/use for the latest compatibility

like image 27
whiscode Avatar answered Oct 05 '22 09:10

whiscode