0
0
SASSmarkup~5 mins

@each loop over maps in SASS

Choose your learning style9 modes available
Introduction

The @each loop helps you repeat styles for many items in a map easily. It saves time and keeps your code neat.

You want to create multiple CSS classes with different colors from a color map.
You need to apply different font sizes to headings stored in a map.
You want to generate button styles for various states stored as key-value pairs.
You have a list of themes with properties and want to create styles for each theme.
Syntax
SASS
@each $key, $value in $map {
  // CSS styles using $key and $value
}

The $key is the map's key (like a name).

The $value is the map's value (like a color or size).

Examples
This creates two button classes with background colors from the map.
SASS
$colors: (primary: #06c, secondary: #ccc);

@each $name, $color in $colors {
  .btn-#{$name} {
    background-color: $color;
  }
}
This sets font sizes for headings named hsmall, hmedium, and hlarge.
SASS
$fonts: (small: 0.8rem, medium: 1rem, large: 1.2rem);

@each $size, $value in $fonts {
  h#{$size} {
    font-size: $value;
  }
}
Sample Program

This code creates three CSS classes: .theme-light, .theme-dark, and .theme-blue. Each class sets a background color from the map. The text color changes to black for the light theme and white for others. Padding, rounded corners, and spacing are added for style.

SASS
@use "sass:map";

$themes: (
  light: #fff,
  dark: #000,
  blue: #00f
);

@each $name, $color in $themes {
  .theme-#{$name} {
    background-color: $color;
    color: if($name == light, #000, #fff);
    padding: 1rem;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
  }
}
OutputSuccess
Important Notes

Use #{$variable} to insert variables inside selectors or property names.

Maps store pairs like a dictionary: keys and values.

You can use if() inside styles to choose values based on conditions.

Summary

@each loops over map keys and values to create repeated styles.

Use $key and $value to access each pair inside the loop.

This helps keep your CSS DRY (Don't Repeat Yourself) and easy to update.