Bird
Raised Fist0
SASSmarkup~15 mins

@each loop over maps in SASS - Deep Dive

Choose your learning style10 modes available
Overview - @each loop over maps
What is it?
The @each loop in Sass lets you repeat a block of styles for each item in a list or map. When used with maps, it helps you access both keys and values easily. This means you can write less code and keep your styles organized. It’s like telling Sass to do the same thing for many pairs of related data.
Why it matters
Without @each loops over maps, you would have to write repetitive CSS for each style variation manually. This wastes time and makes your code harder to update or fix. Using @each with maps saves effort and reduces mistakes, especially when managing many related styles like colors or sizes. It makes your stylesheets smarter and easier to maintain.
Where it fits
Before learning @each loops over maps, you should understand basic Sass syntax, variables, and simple @each loops over lists. After this, you can explore more advanced Sass features like functions, mixins, and control directives to build dynamic stylesheets.
Mental Model
Core Idea
An @each loop over a map runs a block of code once for every key-value pair, letting you use both parts inside the loop.
Think of it like...
Imagine a box of labeled jars where each jar has a name (key) and a flavor (value). Using @each over a map is like tasting each jar and writing down a recipe using both the jar’s name and its flavor.
Map example:
┌───────────────┐
│ (key) : value │
├───────────────┤
│ primary : #06c│
│ secondary : #ccc│
│ accent : #f90 │
└───────────────┘

@each loop:
┌─────────────────────────────┐
│ For each (key, value) in map │
│   Use key and value inside   │
│   the loop block             │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Sass Maps
🤔
Concept: Learn what a Sass map is and how it stores key-value pairs.
A Sass map is like a list but with pairs: each key points to a value. For example: $colors: (primary: #06c, secondary: #ccc, accent: #f90); You can get a value by its key using map-get($colors, primary), which returns #06c.
Result
You can store related data in one variable and access each value by its key.
Knowing maps lets you organize related style data clearly, making your code easier to read and update.
2
FoundationBasic @each Loop Over Lists
🤔
Concept: Learn how @each loops repeat code for each item in a list.
Example: $fonts: (Arial, Helvetica, sans-serif); @each $font in $fonts { .font-#{$font} { font-family: $font; } } This creates classes for each font in the list.
Result
Sass generates CSS classes for each font name automatically.
Understanding @each loops over lists prepares you to use them with more complex data like maps.
3
IntermediateLooping Over Maps With Key and Value
🤔Before reading on: do you think @each over a map gives you just values or both keys and values? Commit to your answer.
Concept: Learn that @each loops over maps provide both the key and the value for each pair.
Syntax: @each $key, $value in $map { // use $key and $value } Example: $colors: (primary: #06c, secondary: #ccc); @each $name, $color in $colors { .text-#{$name} { color: $color; } } This creates classes with color styles using both keys and values.
Result
CSS classes .text-primary and .text-secondary with correct colors are generated.
Knowing you get both key and value lets you write flexible styles that adapt to your data structure.
4
IntermediateUsing Map Keys and Values in Selectors
🤔Before reading on: do you think you can use map keys directly inside CSS selectors? Commit to your answer.
Concept: Learn how to insert map keys into selectors or property names using interpolation.
You can use #{$key} inside selectors or property names to create dynamic styles. Example: @each $name, $color in $colors { .btn-#{$name} { background-color: $color; } } This creates .btn-primary and .btn-secondary classes with background colors.
Result
CSS with dynamic class names based on map keys is generated.
Using interpolation with keys makes your CSS scalable and easy to maintain.
5
IntermediateNested Maps and @each Loops
🤔Before reading on: do you think @each can loop over nested maps directly, or do you need extra steps? Commit to your answer.
Concept: Learn how to loop over maps inside maps by nesting @each loops.
Example: $themes: ( light: (bg: #fff, text: #000), dark: (bg: #000, text: #fff) ); @each $theme, $colors in $themes { .theme-#{$theme} { @each $prop, $value in $colors { #{$prop}: $value; } } } This creates styles for each theme with background and text colors.
Result
CSS classes .theme-light and .theme-dark with correct nested styles are generated.
Understanding nested loops lets you handle complex style data structures cleanly.
6
AdvancedPerformance and Compilation Considerations
🤔Before reading on: do you think using many @each loops over large maps slows down Sass compilation significantly? Commit to your answer.
Concept: Learn how @each loops over maps affect Sass compilation and how to optimize them.
Each @each loop runs at compile time, generating CSS for every pair. Large maps with many loops can increase compile time and output size. To optimize, keep maps focused, avoid unnecessary nesting, and reuse styles with mixins or functions.
Result
You understand how to balance dynamic styles with compile performance.
Knowing compilation costs helps you write efficient Sass that scales well in projects.
7
ExpertAdvanced Map Manipulation Inside @each Loops
🤔Before reading on: do you think you can modify maps or create new maps inside @each loops? Commit to your answer.
Concept: Learn how to combine @each loops with map functions to transform or build new maps dynamically.
Sass functions like map-merge and map-remove let you create new maps inside loops. Example: $new-map: (); @each $key, $value in $old-map { $new-map: map-merge($new-map, ($key: lighten($value, 10%))); } This builds a new map with lighter colors. You can then loop over $new-map to generate styles.
Result
You can dynamically create and use transformed maps for complex styling.
Understanding map manipulation inside loops unlocks powerful dynamic styling patterns beyond static data.
Under the Hood
When Sass processes an @each loop over a map, it reads the map’s key-value pairs one by one. For each pair, it assigns the key and value to the loop variables, then runs the code block inside the loop. This happens at compile time, so the output CSS is fully generated before the browser sees it. Sass uses its internal parser and evaluator to handle interpolation and nested loops, building the final CSS text.
Why designed this way?
Sass was designed to extend CSS with programming features while keeping output CSS simple and fast. The @each loop over maps lets developers write DRY (Don’t Repeat Yourself) code by automating repetitive style generation. Maps provide structured data storage, and looping over them fits naturally with CSS’s repetitive patterns like themes or variants. Alternatives like manual repetition were error-prone and hard to maintain.
Sass Compiler Flow:
┌───────────────┐
│ Source Sass   │
│ with @each    │
│ over maps     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Sass Parser   │
│ reads map     │
│ and loop vars │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Loop Execution│
│ runs block    │
│ for each pair │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ CSS Output    │
│ generated    │
│ with all     │
│ styles       │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does @each over a map give you just values or both keys and values? Commit to your answer.
Common Belief:People often think @each loops over maps only provide the values, like lists.
Tap to reveal reality
Reality:In Sass, @each over maps always provides both the key and the value for each pair.
Why it matters:Assuming only values leads to errors or missing keys in selectors, causing incorrect or missing styles.
Quick: Can you modify a map inside an @each loop directly? Commit to yes or no.
Common Belief:Some believe you can change the original map inside an @each loop by assigning new values.
Tap to reveal reality
Reality:Sass variables are immutable inside loops; you cannot change the original map directly but can create new maps by merging.
Why it matters:Trying to modify maps directly causes confusion and bugs because changes don’t persist as expected.
Quick: Does using many nested @each loops always slow down Sass compilation noticeably? Commit to your guess.
Common Belief:Many think nested @each loops always cause big performance problems.
Tap to reveal reality
Reality:While nested loops add compile time, Sass is efficient; problems only arise with very large or deeply nested maps.
Why it matters:Overestimating performance costs may lead to premature optimization or avoiding useful patterns.
Quick: Is it possible to use map keys directly in CSS selectors without interpolation? Commit to yes or no.
Common Belief:Some believe you can write selectors with map keys directly without interpolation.
Tap to reveal reality
Reality:You must use interpolation (#{$key}) to insert map keys into selectors or property names.
Why it matters:Not using interpolation causes invalid CSS or compilation errors.
Expert Zone
1
When looping over maps, the order of pairs is not guaranteed because Sass maps are unordered collections, so relying on order can cause subtle bugs.
2
Interpolation inside @each loops can affect CSS specificity and selector generation, so careful naming conventions are important to avoid conflicts.
3
Combining @each loops with functions like map-merge allows dynamic map creation, enabling advanced theming and style variations without manual repetition.
When NOT to use
Avoid using @each loops over very large maps or deeply nested maps in performance-critical builds; instead, consider generating styles with mixins or external preprocessing. Also, for simple repeated styles without key-value pairs, plain lists with @each loops are simpler and more efficient.
Production Patterns
In real projects, @each loops over maps are used for theming systems (colors, fonts), responsive breakpoints, and utility class generation. Teams often store design tokens in maps and loop over them to produce consistent, scalable CSS frameworks.
Connections
Data Structures (Computer Science)
Builds-on
Understanding Sass maps as key-value stores connects to the general concept of dictionaries or hash maps in programming, helping learners grasp data organization and retrieval.
Template Engines (Web Development)
Similar pattern
Like @each loops over maps in Sass, template engines loop over data objects to generate repeated HTML, showing a common pattern of data-driven code generation.
Cooking Recipes (Everyday Life)
Builds-on
Just as recipes use ingredient lists with quantities (keys and values) to prepare dishes repeatedly, @each loops over maps automate style creation from structured data.
Common Pitfalls
#1Trying to loop over a map with only one variable instead of two.
Wrong approach:@each $color in $colors { .btn-#{$color} { color: $color; } }
Correct approach:@each $name, $color in $colors { .btn-#{$name} { color: $color; } }
Root cause:Misunderstanding that maps provide key-value pairs, not just values, so two variables are needed to access both.
#2Using map keys directly in selectors without interpolation.
Wrong approach:@each $name, $color in $colors { .btn-$name { color: $color; } }
Correct approach:@each $name, $color in $colors { .btn-#{$name} { color: $color; } }
Root cause:Not knowing that Sass requires interpolation to insert variables inside selectors or property names.
#3Trying to modify the original map inside an @each loop by direct assignment.
Wrong approach:@each $key, $value in $colors { $colors: map-merge($colors, ($key: lighten($value, 10%))); }
Correct approach:$new-colors: (); @each $key, $value in $colors { $new-colors: map-merge($new-colors, ($key: lighten($value, 10%))); }
Root cause:Sass variables are immutable inside loops; you must create a new map instead of modifying the original.
Key Takeaways
Sass @each loops over maps let you run code for every key-value pair, giving you both parts to use inside the loop.
Maps organize related style data clearly, and looping over them reduces repetition and errors in your CSS.
Interpolation (#{$key}) is required to use map keys inside selectors or property names dynamically.
Nested maps and loops let you handle complex style data structures like themes or variants cleanly.
Understanding Sass’s compile-time behavior and map immutability helps you write efficient, maintainable stylesheets.

Practice

(1/5)
1. What does the @each loop do when used with a map in Sass?
easy
A. It creates a new map from the keys only.
B. It deletes all map entries after looping.
C. It repeats styles for each key-value pair in the map.
D. It converts the map into a list.

Solution

  1. Step 1: Understand the purpose of @each with maps

    The @each loop iterates over each key-value pair in a map.
  2. Step 2: Identify what happens during iteration

    For each pair, it repeats the block of styles or code inside the loop.
  3. Final Answer:

    It repeats styles for each key-value pair in the map. -> Option C
  4. Quick Check:

    @each loops over map pairs = repeats styles [OK]
Hint: Remember: @each repeats code for each map pair [OK]
Common Mistakes:
  • Thinking @each deletes map entries
  • Confusing map keys with list items
  • Assuming it converts maps to lists
2. Which of the following is the correct syntax to loop over a map $colors with @each in Sass?
easy
A. @each $key $value in $colors { ... }
B. @each $colors in $key, $value { ... }
C. @each $value, $key in $colors { ... }
D. @each $key, $value in $colors { ... }

Solution

  1. Step 1: Recall the correct @each syntax for maps

    The syntax requires two variables separated by a comma, then in, then the map name.
  2. Step 2: Match the syntax to the options

    @each $key, $value in $colors { ... } correctly uses @each $key, $value in $colors. Others have wrong order or missing comma.
  3. Final Answer:

    @each $key, $value in $colors { ... } -> Option D
  4. Quick Check:

    Two variables separated by comma + in + map name [OK]
Hint: Use comma between key and value, then 'in' before map [OK]
Common Mistakes:
  • Swapping key and value order
  • Missing comma between variables
  • Using wrong variable order or syntax
3. Given the Sass map and code:
$themes: (light: #fff, dark: #000); @each $name, $color in $themes { .#{$name}-theme { background: $color; } }
What CSS will this generate?
medium
A. .light-theme { background: #fff; } .dark-theme { background: #000; }
B. .light { background: #fff; } .dark { background: #000; }
C. .theme-light { background: #fff; } .theme-dark { background: #000; }
D. .light-theme { background: light; } .dark-theme { background: dark; }

Solution

  1. Step 1: Understand the map and loop variables

    The map has keys light and dark with colors #fff and #000.
  2. Step 2: Analyze the generated CSS selectors and properties

    The selector uses interpolation .#{$name}-theme producing .light-theme and .dark-theme. The background uses the color value.
  3. Final Answer:

    .light-theme { background: #fff; } .dark-theme { background: #000; } -> Option A
  4. Quick Check:

    Interpolation creates .light-theme and .dark-theme with correct colors [OK]
Hint: Interpolation with #{} creates dynamic class names [OK]
Common Mistakes:
  • Forgetting interpolation syntax
  • Using keys as colors instead of values
  • Mixing up class name order
4. Identify the error in this Sass code:
$sizes: (small: 1rem, medium: 2rem); @each $size in $sizes { .btn-#{$size} { font-size: $size; } }
medium
A. Missing comma between key and value in @each loop.
B. Using only one variable for a map instead of two.
C. Incorrect interpolation syntax in class name.
D. Map keys and values are reversed.

Solution

  1. Step 1: Check the @each loop variables

    The map has key-value pairs, so the loop needs two variables separated by a comma.
  2. Step 2: Identify the problem with one variable

    The code uses only $size instead of $key, $value, so it cannot access both parts of the map.
  3. Final Answer:

    Using only one variable for a map instead of two. -> Option B
  4. Quick Check:

    Maps need two variables in @each loops [OK]
Hint: Use two variables for maps in @each loops [OK]
Common Mistakes:
  • Using one variable for map iteration
  • Forgetting comma between variables
  • Misusing interpolation syntax
5. You have a Sass map:
$shadows: (none: 0 0 0 transparent, light: 0 1px 3px rgba(0,0,0,0.12), heavy: 0 4px 6px rgba(0,0,0,0.3));

Write a @each loop that creates classes .shadow-none, .shadow-light, and .shadow-heavy with the correct box-shadow property. Which code snippet is correct?
hard
A. @each $name, $shadow in $shadows { .shadow-#{$name} { box-shadow: $shadow; } }
B. @each $shadow, $name in $shadows { .shadow-#{$name} { box-shadow: $shadow; } }
C. @each $name in $shadows { .shadow-#{$name} { box-shadow: $name; } }
D. @each $name, $shadow in $shadows { .shadow-#{$shadow} { box-shadow: $name; } }

Solution

  1. Step 1: Identify correct variable order for map iteration

    Maps use @each $key, $value in $map, so $name is key and $shadow is value.
  2. Step 2: Check class name and property usage

    The class uses interpolation with the key $name, and the property uses the value $shadow.
  3. Final Answer:

    @each $name, $shadow in $shadows { .shadow-#{$name} { box-shadow: $shadow; } } -> Option A
  4. Quick Check:

    Key first, value second, use interpolation for class [OK]
Hint: Map loops: key first, value second, interpolate key for class [OK]
Common Mistakes:
  • Swapping key and value variables
  • Using only one variable for map
  • Interpolating value instead of key in class name
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard