Reputation: 767
I like the way Tailwind defines the colors and would like to use that outside of a Tailwind project.
For that I have defined two colors that I am already generating as classes (bg-|text-):
I would like to (if possible) generate the appropriate SCSS variables.
e.g. $blue-300: #183f6d;
Is that possible?
$tailwind-colors: ("blue-900": #183f6d, "blue-300": #c4cddd);
@each $name, $hexcode in $tailwind-colors {
// Generate Variables
// #{$name}: $hexcode; <--- 👈
// Generate Classes
.hover\:text-#{$name}:hover,
.text-#{$name} {
color: $hexcode;
}
.hover\:bg-#{$name}:hover,
.bg-#{$name} {
background-color: $hexcode;
}
}
Upvotes: 2
Views: 543
Reputation: 767
I received a response to my request from @SassCSS on Twitter:
Sass intentionally doesn't support this, because it makes it very hard for both people and the compiler to figure out where a given variable comes from. We recommend explicitly accessing the map using map.get() instead
Source: Tweet
The solution for me, is therefore to create the variables as SCSS variables and then use them there:
// Syntax: https://tailwindcss.com/docs/customizing-colors
$bg-blue-900: #004070;
$bg-blue-700: #537AA2;
$bg-blue-300: #C1CCDD;
$bg-blue-50: #EAEDF3;
$white: #FFF;
$black: #000;
// Define Tailwind Colors
$tailwind-colors: (
"white": $white,
"black": $black,
"blue-900": $bg-blue-900,
"blue-700": $bg-blue-700,
"blue-300": $bg-blue-300,
"blue-50": $bg-blue-50
);
The other way around it would then also work with map-get:
//@debug map-get($tailwind-colors, white);
//$white: map-get($tailwind-colors, "white");
Source: map-get
Upvotes: 1
Reputation: 8069
You can achieve this if you do it as a separate function inside the :root
element of your SCSS file.
$tailwind-colors: ("blue-300": #183f6d, "blue-900": #c4cddd);
// Generate Variables
:root {
@each $name, $hexcode in $tailwind-colors {
--#{$name}: #{$hexcode};
}
}
@each $name, $hexcode in $tailwind-colors {
// Generate Classes
.text-#{$name} {
color: $hexcode;
}
.bg-#{$name} {
background-color: $hexcode;
}
}
This will result in formatted CSS:
:root {
--blue-300: #183f6d;
--blue-900: #c4cddd;
}
.text-blue-300 {
color: #183f6d;
}
.bg-blue-300 {
background-color: #183f6d;
}
.text-blue-900 {
color: #c4cddd;
}
.bg-blue-900 {
background-color: #c4cddd;
}
See this CodePen example where you can see the compiled CSS with the dropdown button right top.
Upvotes: 1