sai
sai

Reputation: 533

Using hex-code in scss class name to generate css color class of same hex-code

I am trying to define global colors, and I wrote a scss compiler to compile all color to its respective class names, But when I try to use them in my html div, the color is not applying to it.

scss snippet:

$blue-1: #001233;
$blue-2: #002132;
$blue-3: #004237;
$blue-4: #003027;
$blue-5: #CCCCCC;
$blue-6: #FFFFFF;

$allcolors:$blue-1 $blue-2 $blue-3 $blue-4 $blue-5 $blue-6;

@each $color in $allcolors {
    
    .color-#{nth($color, 1)} {
      color: nth($color, 1);
    }
  }

I am calling this in my html div as

<div class="color-#CCCCCC">TEST</div>

I don't see my style applied & when I tried compiling it, I can see my css style compiled as shown below

.color-#001233 {
    color: #001233;
}

.color-#002132 {
    color: #002132;
}

.color-#004237 {
    color: #004237;
}

.color-#003027 {
    color: #003027;
}

.color-#CCCCCC {
    color: #CCCCCC;
}

.color-#FFFFFF {
    color: #FFFFFF;
}

any help would be appreciated.

Upvotes: 1

Views: 1711

Answers (1)

Temani Afif
Temani Afif

Reputation: 273990

You need to escape the # in your CSS file since it's a special character used for ID selector.

.color-\#CCCCCC {
    color: #CCCCCC;
}
<div class="color-#CCCCCC">TEST</div>

you can adjust your SCSS accordingly to add \

$blue-1: #001233;
$blue-2: #002132;
$blue-3: #004237;
$blue-4: #003027;
$blue-5: #CCCCCC;
$blue-6: #FFFFFF;

$allcolors:$blue-1 $blue-2 $blue-3 $blue-4 $blue-5 $blue-6;

@each $color in $allcolors {
    .color-#{unquote("\\" + $color)} {
      color: $color;
    }
  }

Upvotes: 2

Related Questions