Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a sass variable in an @each loop

Tags:

sass

I'm trying to create a little overview for all the colors we use in our corporate identity. All our colors have been defined in _settings-colors.scss, and the only reason I need this bit of css is for the library, where the colors need to be listed.

What I have now is as follows:

$colors-brand: color-brand, color-brand-40, color-brand-60, color-brand-70;

.prfx-color {
    display: block;
    height: 5rem;
    width: 100%;

    @each $color in $colors-brand {
        &--#{$color} {
            background-color: #{'$'+$color};

            &::after {
                content: '$'+$color;
            }
        }
    }
}

These color-brand variables are set in another file which I'm including in this scss file.

The code above outputs this:

.prfx-color {
  display: block;
  height: 5rem;
  width: 100%;
}
.prfx-color--color-brand {
    background: $color-brand;
}
.prfx-color--color-brand::after {
    content: "$color-brand";
} [...etc]

What I'm after however, is this:

.prfx-color--color-brand {
    background: #00ff11; // don't worry, brand is not actually this color
}

The problem I'm having is that the $color-brand variable isn't interpreted as a sass variable anymore, but is a literal value. I need the #hheexx that this variable refers to!

All the solutions I've found so far consist of using two lists, or a key-value pair. In my situation these variables have already been set once, and I want a solution where I don't want to have to manually edit the library if the colors change.

Is this at all possibe, or am I too greedy here?

like image 647
Kablam Avatar asked Nov 27 '25 03:11

Kablam


1 Answers

And I realized I overcomplicated it. You don't need any extra functions because the @each is designed to work with maps and iterating over multiple values.

$cool: blue;
$mad: red;

$colors: (
  cool: $cool,
  mad: $mad
);

.prfx-color {
  @each $key, $val in $colors {
    &--#{$key} {
      background-color: $val;

      &::after { content: "$#{$key}"; }
    }
  }
}
like image 104
Ari Avatar answered Dec 02 '25 06:12

Ari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!