Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to use CSS Variables in SASS functions?

Tags:

I have defined a color in my root:

:root { --purple: hsl(266, 35%, 70%); } 

And I'm trying to use it in a SASS function to give it transparency:

.purple {   background: transparentize(#{"var(--primary-color)"}, 0.7) } 

Does anyone know of a way to get this to work? Or is it just not possible?

like image 376
sammiepls Avatar asked Aug 17 '18 03:08

sammiepls


People also ask

Can you use CSS variables with Sass?

Sass variables are all compiled away by Sass. CSS variables are included in the CSS output. CSS variables can have different values for different elements, but Sass variables only have one value at a time.

How do you use variables 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.

How do I assign a Sass variable to a variable in CSS?

To convert the SASS variable to a CSS custom property you put curly brackets around it, and a hash in front. If you've used template literals in JavaScript it's the same thing, just with a # instead of a $ (because we already have $ in the variable name).

Can you change SCSS variable value dynamically?

We can dynamically update SCSS variables using ReactJS with the help of a project by achieving theme switching of the card component between light and dark theme. Prerequisite: Basic knowledge of npm & create-react-app command.


2 Answers

Global variables can be defined outside of an element in a :root pseudo-class:

:root {   --color-background: #FFFFFF; } 

you can define a function like this:

@function color($color-name) {   @return var(--color-#{$color-name}); } 

and call it into your sass:

body {    color: color(primary);  } 

compiled sass code is:

body {    color: var(--color-primary);  } 
like image 111
Keivan Sina Avatar answered Sep 18 '22 13:09

Keivan Sina


#{var(--variablename)} 

This is how you use CSS variables in SCSS

like image 20
Shubham Gaikwad Avatar answered Sep 19 '22 13:09

Shubham Gaikwad