How I can display this Color Palette with HEX and RGB formats by using @each loop
Color Palette Variable :
$colors: (
"transparent": transparent,
"current": currentColor,
"white": (
hex: #FFFFFF,
rgb: (255, 255, 255)
),
"black": (
hex: #000000,
rgb: (0, 0, 0)
)
) !default;
The result that I expected after compiling to CSS :
.color-transparent {
color: transparent;
}
.color-current {
color: currentColor;
}
.color-white {
--color-opacity: 1;
color: #FFFFFF;
color: rgba(255, 255, 255, var(--color-opacity));
}
.color-black {
--color-opacity: 1;
color: #000000;
color: rgba(0, 0, 0, var(--color-opacity));
}
Here's how you do it with @each
and the map.
$colors: (
"transparent": transparent,
"current": currentColor,
"white": (
hex: #FFFFFF,
rgba: (255, 255, 255, var(--color-opacity))
),
"black": (
hex: #000000,
rgba: (0, 0, 0, var(--color-opacity))
)
) !default;
// $COLOR = KEY, $VALUE = VALUE, $COLORS = MAP
@each $color, $value in $colors {
// SINGLE VALUE
@if $color == "transparent" {
.color-#{$color} {
color: #{$value};
}
} @else if $color == "current" {
.color-#{$color} {
color: $value;
}
// SUBMAP - SINCE $VALUE IS ANOTHER MAP HERE.
} @else {
// SET THE COLOR NAME
.color-#{$color} {
// SET YOUR COLOR OPACITY
--color-opacity: 1;
// LOOP THROUGH THE TWO COLORS IN THE SUBMAP
@each $color_name, $value_c in $value {
@if $color_name == hex {
color: $value_c;
} @else {
color: rbga( $value_c );
}
}
}
}
}
.color-transparent {
color: transparent;
}
.color-current {
color: currentColor;
}
.color-white {
--color-opacity: 1;
color: #FFFFFF;
color: rbga(255, 255, 255, var(--color-opacity));
}
.color-black {
--color-opacity: 1;
color: #000000;
color: rbga(0, 0, 0, var(--color-opacity));
}
To fix the issue if rgba()
is throwing the channels error, you can remove the @else
after the hex
section and pass the hex value into the rgba()
function. This will convert the hex to an rgb value.
$colors: (
"transparent": transparent,
"current": currentColor,
"white": (
hex: #FFFFFF,
rgba: (255, 255, 255, var(--color-opacity))
),
"black": (
hex: #000000,
rgba: (0, 0, 0, var(--color-opacity))
)
) !default;
// $COLOR = KEY, $VALUE = VALUE, $COLORS = MAP
@each $color, $value in $colors {
// SINGLE VALUE
@if $color == "transparent" {
.color-#{$color} {
color: #{$value};
}
} @else if $color == "current" {
.color-#{$color} {
color: $value;
}
// SUBMAP - SINCE $VALUE IS ANOTHER MAP HERE.
} @else {
// SET THE COLOR NAME
.color-#{$color} {
// SET YOUR COLOR OPACITY
--color-opacity: 1;
// LOOP THROUGH THE TWO COLORS IN THE SUBMAP
@each $color_name, $value_c in $value {
// WE ONLY WANT TO USE HEX, BECAUSE RGBA() IS A NATIVE FUNCTION
@if $color_name == hex {
color: $value_c;
color: rgba( $value_c, var(--color-opacity));
}
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.