0
0
SASSmarkup~15 mins

@each loop over maps in SASS - Deep Dive

Choose your learning style9 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.