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
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With