Home > database >  SCSS create a partial named generic class
SCSS create a partial named generic class

Time:10-29

Is it possible to have a partial named class like this

.theme-color- {
  &yellow {
    color: yellow
  }
  &red {
    color: red
  }
  &blue {
    color: blue
  }
}

but a generic way like this

$yellow = yellow;
$red = red;
$blue = blue;

.theme-color-#{$my-color} {
  color: #{$my-color};
}
<div class="theme-color-red"></div>

CodePudding user response:

You can use @each:

$colors: red, yellow, blue;

@each $color in $colors {
  .theme-color-#{$color} {
    color: $color;
  }
}

This generates the following CSS:

.theme-color-red {
  color: red;
}

.theme-color-yellow {
  color: yellow;
}

.theme-color-blue {
  color: blue;
}

You can also use @each with a map instead of a list if you want to specify custom color values:

$colors: (red: '#ff0000', yellow: '#fffd62', blue: '#0000ff');

@each $color, $hex in $colors {
  .theme-color-#{$color} {
    color: $hex;
  }
}

Which results in the following CSS:

.theme-color-red {
  color: "#ff0000";
}

.theme-color-yellow {
  color: "#fffd62";
}

.theme-color-blue {
  color: "#0000ff";
}
  • Related