Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS: Set variable at compile time

Is it possible to set a sass variable at compile time? I basically want to do this:


$color: red !default;
div#head {

  background-color: $color;

}

When I compile to css I want to set $color to "blue" (preferably from the command line). Has anyone been able to do this?

Thanks, Chris

like image 516
Kenzic Avatar asked Apr 08 '11 00:04

Kenzic


People also ask

Can you change SCSS variable value dynamically?

CSS Variables to the Rescue CSS variables is a standard which enables you to have variables in CSS. SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time.

How can we set default value to the variable Sass?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.

How do I declare 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 the same as SCSS?

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

I found this at their FAQ http://sass-lang.com/docs/yardoc/file.FAQ.html

If you just want to pass some variables to the CSS every time it gets compiled, like using --watch, you can use Sass functions to define Ruby scripts to even query a database. But the code is going to be compiled only once, and served statically.

But if you need to recompile it at every request with different options,

you can use Sass::Engine to render the code, using the :custom option to pass in data that can be accessed from your Sass functions

Seems like it's not recommended, though. Probably for performance reasons.

like image 115
Caio Cunha Avatar answered Oct 22 '22 16:10

Caio Cunha


An alternate of command line options is to create other files assigning values to variables.

Assume that your code above is in a file named 'style.scss'. To set $color to "blue", create a file such as:

$color: blue;
@import "style";

and name it to 'blue.scss' for example. Then compile it with below.

sass blue.scss:style.css

When you want to assign another value to the variable, make another file named "green.scss" like:

$color: green;
@import "style";

Then compile it with

sass green.scss:anotherstyle.css

It is bothering somewhat but enables to decide values of variables at compile time.

like image 36
reppets Avatar answered Oct 22 '22 15:10

reppets