Create CSS custom properties from SCSS variables

Issue

I have an SCSS map of colour names and values. I want to create CSS custom properties from them like so:

SCSS

$colours:(
  "gray-500":    #f7fafc,
  "red-500":     #f56565,
  "green-500":   #48bb78
);

Desired resultant CSS

--gray-500:  #f7fafc;
--red-500:   #f56565;
--green-500: #48bb78;

I know how to loop through the map, but where I’m getting caught up is how to use the key as a custom property name, and how to prepend -- to it. All the examples I can find related to this topic involve manually typing out the custom property name – not gleaning it from the key of a map.

This is what I have so far:

@each $colour, $value in $colours {
    --#{$colour}:$value;
}

That generates an error: expected "{" with the caret pointing to the end of this line:

--#{$colour}:$value;

I’m using Dart Sass 1.23.7

Solution

On SCSS to CSS you can use the following:

:root {
  $colours:(
    "gray-500": #f7fafc,
    "red-500": #f56565,
    "green-500": #48bb78
  );

  @each $key_name, $value in $colours {
    --#{$key_name}: #{$value};
  }
}

demo on jsfiddle.net

On SASS to CSS you have to use the @each inside a :root element (or defining an element inside):

$colours:(
  "gray-500": #f7fafc,
  "red-500": #f56565,
  "green-500": #48bb78
);

:root {
  @each $key, $value in $colours {
    --#{$key}: #{$value};
  }
}

Answered By – Sebastian Brosch

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.