max
max

Reputation: 642

How to convert named color to HEX using SCSS?

I have a mixin with named colors:

@mixin color-classes-rendering {
    $colors: (
        rebeccapurple
    );

    @each $value in $colors {
        .#{nw}-#{nth($value, 1)}#{" > span"} {
            background-color: nth($value, 1);
        }
    }
}

Here is compiled CSS:

.nw-rebeccapurple > span {
    background-color: rebeccapurple;
}

I don't know why, but "rebeccapurple" doesn't shown in Chrome at Android. Is it possible to convert it to this one:

.nw-rebeccapurple > span {
    background-color: #663399;
}

Upvotes: 1

Views: 3179

Answers (2)

cimmanon
cimmanon

Reputation: 68339

While Sass does provide functions to extract the individual R, G, and B values for any given color, it doesn't provide a convenient way to convert those to hexadecimal. It would be simpler for you to convert it to the rgb() format.

$color: rebeccapurple;

.foo {
    color: #{'rgb(#{red($color)}, #{green($color)}, #{blue($color)})'};
}

Output:

.foo {
  color: rgb(102, 51, 153);
}

See also: Why does Sass change the format of my colors?


I should also point out that what you've written so far would be better suited to a mapping:

$colors: (
    'rebeccapurple': #639,
    'black': #000
);

@each $name, $color in $colors {
    .nw-#{$name} > span {
        background-color: $color;
    }
}

Output (compressed format):

.nw-rebeccapurple > span { background-color: #639; }

.nw-black > span { background-color: #000; }

Upvotes: 3

max
max

Reputation: 642

My solution is to put the HEX value of each named color manually, like this:

@mixin color-classes-rendering {
    $colors: (
        rebeccapurple   #663399,
        black           #000000
    );

    @each $value in $colors {
        .#{nw}-#{nth($value, 1)}#{" > span"} {
            background-color: nth($value, 2);
        }
    }
}

Upvotes: 1

Related Questions