Scalable, global variable assignment #mixin for Sass - css

I thought that I had already solved this, but the code is not compiling in the way that I intend.
Here is my current code:
$prefix: 'foo';
#mixin var-assign($var, $val) {
$var: $val !global;
};
// will output .foo-selector
.#{$prefix}-selector {
/* ... */
}
#include var-assign($prefix, 'bar');
// should output .bar-selector
.#{$prefix}-selector {
/* ... */
}
The code above prints .foo-selector twice. Where am I going wrong that I am not printing one instance of .foo-selector ad one instance of .bar-selector?

You need to changes in your mixin variable, Try using
#mixin var-assign($prefix, $val) {
$prefix: $val !global;
};
Working example here:

Related

Unable to use CSS Custom Properties (aka CSS Variables) with SASS #if Statement

I'm trying to pass some CSS Custom Properties to a SASS Mixin. I'm able use the variables when applied directly in the styling I want. But when I try to use a variable in an If statement, it doesn't work.
Mixin Example:
#mixin bg-color($hue, $status) {
background: hsl($hue, 50%, 50%); // $hue works as expected
#if $status == 'danger' { // doesn't work!
color: 'red';
} #else if $status == 'warning' { // doesn't work!
color: 'orange';
} #else { // always enters the else branch
color: 'black';
}
}
CSS:
:root {
--hue: 195;
--status: 'default';
}
.demo {
#include bg-color(var(---hue), var(---status));
}
If I manually add the status value to the mixin, it works:
.demo {
#include bg-color(var(---hue), 'danger');
}
Any idea what might be the issue?
UPDATE: As #temani-afif mentioned, this approach isn't possible because SASS files are compiled before CSS variables are used.
If you have some file, where you import all SCSS files, it depends which is imported first and which are imported after.
Make sure that one that you need to be Read by VS is first.
For example i needed to read first my variables, so it have to be first, other way, my code read mixin, and doesnt know yet what is '$blue'.

SASS mixin outputs function in compiled CSS

My compiled CSS when viewed has a SASS function in it that was never compiled. This is presumably caused by the mixin I'm using to auto generate classes. I have no idea how to fix it.
SASS code:
$rsColors: (
main: (
base: #333030,
lighter:#827a7a,
light:#5a5555,
dark:#0c0b0b,
darker:#000000,
red: #211010,
accent:#999595,
border: #666666
),
link: (
base: #c42727,
lighter:#eb9999,
light:#de5959,
dark:#841a1a,
darker:#440e0e,
hover:#841a1a,
bg:rgba(80, 80, 80, 0.8),
bgHover: #cccccc
)
}
#mixin modifiers($map, $attribute, $prefix: '-', $hover: 'false', $separator: '-',$base: 'base', $type: 'darken', $perc: '15%') {
#each $key, $value in $map {
&#{if($key != $base, #{$prefix}#{$key}, '')} {
#if type-of($value) == 'map' {
#include modifiers($value, $attribute, $separator, $hover);
}
#else {
#{$attribute}: $value;
#if $hover == 'true' {
&:hover {
$function: get-function($type);
#{$attribute}: call($function,$value,$perc);
}
}
}
}
}
}
.rsBg {
#include modifiers($rsColors, 'background', $hover: 'true');
}
Compiled CSS (as viewed from style editor in Firefox inspector):
...
.rsBg-yellow-700 {
background: #b7791f;
}
.rsBg-yellow-700:hover {
background: darken(#b7791f, 15%);
}
...
How can I fix the compiled CSS so it's rendered correctly? I figure the mixin is to blame since it's outputting what I'm telling it to. Why it's not compiling before being output to CSS?
Expected Output:
...
.rsBg-yellow-700 {
background: #b7791f;
}
.rsBg-yellow-700:hover {
background: #915300; //assuming 15% darken
}
...
**Edit**
After some testing I have found I needed to add the ```get-function()``` method to get ```call()``` to work. However, no matter what I try I can not get the ```$perc``` variable in such a way as to not throw a "not a number" error. I can hard code percentages and it will compile without errors.. but I'd rather not have to do that.
The problem actually comes from the way you call the function and not the mixin. Instead of:
#{$attribute}: unquote(#{$type}($value, #{unquote($perc)}));
You should use the built-in function call() as below:
#{$attribute}: call($type, $value, $perc);
You also need to remove the quotation marks for the parameter $perc or you will get an error such as: $amount: "15%" is not a number for 'darken'. I tried to remove them with unquote() but it doesn't seem to work.
The answer to this issue was the use of '' in the arguments. Specifically the $lightness variable (which was changed from the #perc variable). Once I removed the quotes and just let it hang there, everything compiled and worked fine.
I removed the $type variable and changed the function to scale_color as it seemed to fit better with what I wanted. I should probably change the argument variable to a different name so not to be confused with the scale_color() argument. A task for a different day though.
PLEASE NOTE: I am accepting #Arkellys answer because it set me on the right path to this answer, and I feel really weird about accepting my own answer. I just added this answer so if another comes along it might help. Thank you #Arkellys for your help!
The final mixin
#mixin modifiers($map, $attribute, $prefix: '-', $hover: 'false', $separator: '-',$base: 'base', $lightness: -15%) {
#each $key, $color in $map {
&#{if($key != $base, #{$prefix}#{$key}, '')} {
#if type-of($color) == 'map' {
#include modifiers($color, $attribute, $separator, $hover);
}
#else {
#{$attribute}: $color;
#if $hover == 'true' {
&:hover {
#{$attribute}: scale_color($color,$lightness: $lightness);
}
}
}
}
}
}
.rsBg {
#include modifiers($rsColors, 'background', $hover: 'true', $lightness: -20%);
}

SASS mixin is included even though class doesn't exist

I created two mixins which assign different values to the same variable that I want to use later in the header background url.
Depending on the html class variable $image-name should be different since I include different mixins but it always has a "second-img" value even though class .second doesn't exist in my html.
Please let me know if there is a better way to do this.
Thanks!
#mixin first-image($image) {
$image-name: $image !global;
}
#mixin second-image($image) {
$image-name: $image !global;
}
html.first {
#include first-image("first-img");
}
html.second {
#include second-image("second-img");
}
header {
background-image: url(../images/#{$image-name}-banner.jpg);
}
Your code when executed looks like this:
html.second {
second-img {
$image-name: second-img !global;
}
}
Your mixing is pulling in the value of $image that you defined during the #include as they have the same variable names.
#mixin second-image($image) {
$image-name: $image !global;
}
Change the variable name to something else and it won't display the same:
#mixin second-image($image) {
$image-name: $thingy !global;
}

CSS variables with fallback for older browsers

TL;DR: How can you use SCSS to have CSS variables with a fallback for older browsers.
I'm trying to make sense of this article. In my opinion, you have to already be an advanced SASS user to understand it, which I'm not. To make matters worse, it's the only article I found on the subject.
Here is what I'm trying to achieve:
My scss should be along the lines of :
body {
#include v(background-color, primary)
}
then the processed CSS should be
body{
background: yellow; /* Yellow being defined above as the primary color */
background: var(--color-primary);
}
By playing around a bit, I can already get the value of the CSS variable like so:
$colors: (
primary: yellow,
);
:root {
#each $name, $color in $colors {
--color-#{$name}: $color;
}
}
#mixin background-color($color_) {
background: var(--color-#{$color_});
}
To use it:
body{
#include background-color(primary);
}
Which will result in this:
body {
background: var(--color-primary);
/* But the fallback is missing :(, I tried things with the map-get but it's really eluding me... */
}
If you're using Sass, you can automate fallbacks through a Sass mixin. Create a map of your CSS variable names and their values, and then you can look up those values in a mixin that outputs the fallback style and the preferred one
$vars: (
primary: yellow,
);
:root {
--primary: map-get($vars, primary);
}
#mixin var($property, $varName) {
#{$property}: map-get($vars, $varName);
#{$property}: var(--#{$varName});
}
The above mixin is used like so:
body {
#include var(background-color, primary);
}
and outputs the following CSS:
:root {
--primary: yellow;
}
body {
background-color: yellow;
background-color: var(--primary);
}
Et voilĂ  :)
Update: Postcss Custom properties can do fallback and is way easier than the below code
step 1: declare scss variables
So first of all we want to put some variables in a $map, I'll go with color variables:
$colors: (
primary: #FFBB00,
secondary: #0969A2
);
step 2: automate css 4 var generation
// ripped CSS4 vars out of color map
:root {
// each item in color map
#each $key, $value in $colors {
--colors-#{$key}: $value;
}
}
What happens in root is : for each key and value in the colors map, we print the followng :
--colors-#{$key}: $value;
Which corresponds to css variable declarations. I believe the weird bit with #{} around the key is to not have spaces around the value.
Thus the result is:
--colors-primary: #FFBB00,
--colors-secondary: #0969A2
Note that the prefix (--colors-) is the same name as the scss color map above it. The why will become clear in last step.
step 3: Plenty of maps !
$props: (
background-color: $colors
);
$map-maps: (
background-color: colors
);
Here we add the map $props which maps a css property to the map containing the values. background-color will hold color, so the correct map is $colors.
map-maps is a copy of props where instead of the map we have the name of said map. (this is relative to the note in step 2).
Step 4 : let's make it work !
#mixin v($prop, $var) {
// get the map from map name
$map: map-get($props, $prop);
// fallback value, grab the variable's value from the map
$var-fall: map-get($map, $var);
// our css4 variable output
$var-output: var(--#{$map}-#{$var});
#{$prop}: $var-fall;
// css4 variable output
#{$prop}: $var-output;
}
body{
#include v(background-color, primary);
}
I simplified the code in the article quite a bit, it still works, for this example at least, the code in the article takes more into account.
Anyhow, here is what happens.
First, we call the mixin with:
#include v(background-color, primary);
Then upon entering,
$map: map-get($props, $prop); // map-get($props, background-color)
we have a variable called $map to which we assign the value that is inside the $props map at the key background-color which happen to be the $colors map. It's a bit of a maze but it's not that complicated once you resolve it.
Then for the fallback:
$var-fall: map-get($map, $var);
This simply gets the value of the map we just got (which is $colors) at the $var key (which happens to be primary). Thus the result is #FFBB00.
For the css var
$map-name: map-get($map-maps, $prop);
$var-output: var(--#{$map-name}-#{$var});
we recreate what we did to generate the var in the #each loop
Whole code would be :
$colors: (
primary: #FFBB00,
secondary: #0969A2
);
// ripped CSS4 vars out of color map
:root {
// each item in color map
#each $name, $color in $colors {
--colors-#{$name}: $color;
}
}
$props: (
background-color: $colors,
color: $colors
);
$map-maps: (
background-color: colors
);
#mixin v($prop, $var) {
// get the map from map name
$map: map-get($props, $prop);
// fallback value, grab the variable's value from the map
$var-fall: map-get($map, $var);
// our css4 variable output
$map-name: map-get($map-maps, $prop);
$var-output: var(--#{$map-name}-#{$var});
#{$prop}: $var-fall;
// css4 variable output
#{$prop}: $var-output;
}
body{
#include v(background-color, primary);
}
Now this is a simplification of what is done in the article. You should check it out to have code a bit more robust.
I assume you are aware of the reason why it didn't show the fallback. But since it's an answer I will explain the reasons
The current mixin block has only one background property which makes the sass compiler to generate only one property. I don't think sass can identify whether 'var' is supported in browser or not. So, we have to explicitly specify if we need the fallback.
Since you already have the map all you need is to get the value by giving the key 'primary'
#mixin background-color($color_) {
background: var(--color-#{$color_});
background: map-get($colors, primary);
}
This will add the background: yellow to the body class always. Alternatively if you want to control the addition of the fallback based on condition. You can do like this
#mixin background-color($color_, $showFall) {
background: var(--color-#{$color_});
#if $showFall {
background: map-get($colors, primary);
}
}
and call like this
body{
#include background-color(primary, true);
}
Code pen for the same
https://codepen.io/srajagop/pen/xdovON
Note: I am writing the answer under the assumption that you want only the background-color to work and not all the other properties like mentioned in that post. For that you need to create a proper data structure

Get variable name from variable value in SASS/SCSS

I'd like to access variable within an #each loop using defined value like in the following example:
$car:true;
$people:false;
$job:false;
#mixin options($someval){
#each $prefix in car,people,job{
#if $#{$prefix} == true{
//some CSS...
}
}
}
Variable would be a sort of "semaphores" that define whether print or not Css rules.
My big doubt is how can I check over dynamically defined variables name ?
I've tried with $#{$prefix} but it doesn't work.
EDIT ---------------------------
I'd like to obtain this CSS
car-something: 34px;
Where the word "car" is taken from $prefix and in the first round of #each loop $#{$prefix} becomes $car
The problem is on $#{$prefix} ... it doesn't work :P i get an error
This is an old question but since it has no valid answer, here it is
You need to pass a map to #each
$car:true;
$people:false;
$job:false;
#mixin options($someval){
#each $key, $val in (car: $car, people: $people, job: $job) {
#if $val == true{
#{$key}-something: $someval
}
}
}
test {
#include options(34px)
}
Instead of trying to interpolate a variable name, pass a list to the mixin.
$car: true;
$people: false;
$job: false;
$thing-list: $car, $people, $job;
#mixin thingamajig($thing-list) {
#each $thing in $thing-list {
#if $thing {
// Some CSS
}
}
}

Resources