Looping through a Data Map with Sass

I’ve decided to share this code for anyone who requires a quick ‘copy and paste’ solution for using data maps (map-get) and loops within Sass.

This example will allow you to set values within the data map, then loop through and output as CSS rules.

Setup the variables within the data map and create the code for the loop:

//Badges
$badges: (
    //Badge 1
    1: (
        background: #54677b,
        color: #f1ec69
    ),
    
    //Badge 2
    2: (
        background: #ecebeb,
        color: #ffffff
    ),
    
    //Badge 3
    3: (
        background: #30b59f,
        color: #2f343e
    )
);

//Loop
@each $name, $colors in $badges {
    #badge-#{$name} {
        background:map-get($colors,background);
        color:map-get($colors,color);
    }
}

The compiled CSS will be returned as:

#badge-1 {
  background: #54677b;
  color: #f1ec69;
}

#badge-2 {
  background: #ecebeb;
  color: #ffffff;
}

#badge-3 {
  background: #30b59f;
  color: #2f343e;
}
There are no comments, be the first. Use the form below to add your comment

Post a Comment