DEV Community


Generating variants using Sass

Stephane Rangaya
Designer, Engineer, DevOps
・2 min read

At Ridgeline, we're building a component library that our developers can use to implement our user interface. We have a Badge component that is available in many colors.

We're not using CSS-in-JS yet so we have to change the className of the component based on a prop. This is fairly simple and we end up having one class for each color variant: badge-{color}.

We have two styles of badges: filled and outline. Here's the typical code for styling a badge:

.badge-red {
  &-filled {
    background-color: red;
    color: white;
  &-outline {
    background-color: white;
    box-shadow: inset 0 0 0 0.0625rem red;
    color: red;

We have many colors but for the sake of simplicity, let's say we have the following five colors:

red: #DC143C
green: #228B22
blue: #191970
orange: #FF4500
yellow: #FFD700

We could create a code similar to the one above for each color but Sass has a neat at-rule named @each that makes it easy to emit styles based on a map.

First, we need to create the map:

$colors: (
  'red': '#DC143C',
  'green': '#228B22',
  'blue': '#191970',
  'orange': '#FF4500',
  'yellow': '#FFD700',

Once we've done that, we can use this map to generate the needed badge styles for each of these colors:

@each $name, $color in $colors {
  .badge-${name} {
    &-filled {
      background-color: ${color};
      color: white;
    &-outline {
      background-color: white;
      box-shadow: inset 0 0 0 0.0625rem ${color};
      color: ${color};

Voilà! This will generate everything we need, and if we ever need to add a new variant, all we have to do is to add a color to our map.

We're recruiting!

Feel free to reach out to me on Twitter if you have any questions and if this is the kind of things that's interesting to you, Ridgeline is recruiting in Nevada and New York, you should join us!

Discussion (0)