SASS function darken & lighten not working when using object of colors

Viewed 953

I am trying to use the darken sass function but when I read from the sass object in my scss module, it thinks the color is actually a string and thus the function fails to parse the variable passed in.

variables.scss

$primary: #ae9fec;
$secondary: #d19ac1;

$theme: (
    "primary": ($primary, white),
    "secondary": ($secondary, white)
);

Button.module.scss

@each $colorGroup in $theme {
    &[data-variant="#{nth($colorGroup, 1)}"] {
        background-color: #{nth(nth($colorGroup, 2), 1)}); // this works

        &:hover {
            background-color: darken(#{nth(nth($colorGroup, 2), 1)}), 10%); // this does not because it thinks its a string.  I tried unquote() but that didn't work, still thinks it's a string.
        }
    }
}
1 Answers

If you remove the interpolation in your selector rules (not the selector itself), it should compile as intended.

Here's a test - and I'm assuming you are nesting the @each loop inside a selector or using @at-root, since base-level rules cannot contain the & character like this - with a .button selector for your ruleset:

/* variables.scss */
$primary: #ae9fec;
$secondary: #d19ac1;

$theme: (
    "primary": ($primary, white),
    "secondary": ($secondary, white)
);

/* Button.module.scss */
.button {
    @each $colorGroup in $theme {
        &[data-variant="#{nth($colorGroup, 1)}"] {
            background-color: nth(nth($colorGroup, 2), 1);

            &:hover {
                background-color: darken(nth(nth($colorGroup, 2), 1), 10%);
            }
        }
    }
}

The compiled code looks like this:

.button[data-variant="primary"] {
  background-color: #ae9fec;
}

.button[data-variant="primary"]:hover {
  background-color: #8a74e4; /* Darkened $primary */
}

.button[data-variant="secondary"] {
  background-color: #d19ac1;
}

.button[data-variant="secondary"]:hover {
  background-color: #c177ab; /* Darkened $secondary */
}

I also removed the extra parenthesis in the example.

Related