DEV Community

Anthony Frehner
Anthony Frehner

Posted on • Edited on

1 1

Making CSS vars with SCSS vars

SASS treats CSS variables (also known as custom properties) in a special way, which means it's a little difficult to create CSS vars dynamically:

Sass parses custom property declarations differently than other property declarations. All tokens, including those that look like SassScript, are passed through to CSS as-is.

SASS docs

Which can cause problems, especially for my situation where I want to

  1. Keep the SASS variables around because they're used in a lot of existing code, but also
  2. Add CSS variables for new code

So here's how I've worked around this. It's not ideal, because it still duplicates the name of the SASS variable, but it works for my situation. 🤷

$primary-color: #30dbb4;

@mixin add-css-variable($name, $color) {
  --#{$name}: $color;
}

:root {
  // repeat as necessary for all your vars
  @include add-css-variable('primary-color', $primary-color);
}
Enter fullscreen mode Exit fullscreen mode

You can test this out in the wonderful SassMeister playground

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
teetotum profile image
Martin • Edited

As far as I know string interpolation is processed by sass when creating the css variable and its value:

$my-color: #123456;

.foo {
    --my-color: #{$my-color};
}
Enter fullscreen mode Exit fullscreen mode

will produce:

.foo {
  --my-color: #123456;
}
Enter fullscreen mode Exit fullscreen mode

I tried it on sassmeister. Maybe I'm missing something?

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay