Bird
Raised Fist0
SASSmarkup~15 mins

@each loop over lists in SASS - Deep Dive

Choose your learning style10 modes available
Overview - @each loop over lists
What is it?
The @each loop in Sass is a way to repeat a set of styles for each item in a list. It helps you write less code by automating repetitive CSS rules. Instead of writing the same style many times, you tell Sass to do it for every item in your list. This makes your stylesheets cleaner and easier to manage.
Why it matters
Without the @each loop, you would have to write repetitive CSS code manually, which is time-consuming and error-prone. The loop saves time and reduces mistakes by automating repeated styles. It also makes it easier to update styles because you only change the list, and all related styles update automatically.
Where it fits
Before learning @each loops, you should understand basic Sass syntax, variables, and lists. After mastering @each loops, you can explore nested loops, maps, and functions in Sass to create even more dynamic styles.
Mental Model
Core Idea
The @each loop runs a block of styles once for every item in a list, like giving instructions to repeat a task for each object in a group.
Think of it like...
Imagine you have a box of crayons, and you want to color a page with each crayon one by one. Instead of picking each crayon manually, you tell a robot to pick each crayon from the box and color the page. The robot is like the @each loop doing the same task for every crayon automatically.
List: [red, blue, green]

@each item in list {
  Apply styles for item
}

Result:
- Styles for red
- Styles for blue
- Styles for green
Build-Up - 6 Steps
1
FoundationUnderstanding Sass Lists
🤔
Concept: Learn what lists are in Sass and how to create them.
In Sass, a list is a group of values separated by spaces or commas. For example, $colors: red, blue, green; creates a list of three colors. Lists let you store multiple values in one variable.
Result
You can store multiple items in one variable and use them later.
Knowing how lists work is essential because @each loops go through each item in these lists.
2
FoundationBasic @each Loop Syntax
🤔
Concept: Introduce the basic structure of the @each loop in Sass.
The @each loop looks like this: @each $item in $list { // styles using $item } It repeats the styles inside the block for every item in the list.
Result
You can write one block of styles that applies to every item in a list.
Understanding the syntax lets you automate repetitive CSS rules easily.
3
IntermediateUsing @each with Color Lists
🤔Before reading on: do you think you can use @each to create different background colors for multiple classes? Commit to your answer.
Concept: Apply @each to generate CSS classes with different background colors from a list.
Example: $colors: red, blue, green; @each $color in $colors { .bg-#{$color} { background-color: $color; } } This creates .bg-red, .bg-blue, and .bg-green classes with matching backgrounds.
Result
CSS classes with different background colors are generated automatically.
Using @each with lists lets you create multiple related styles quickly and consistently.
4
IntermediateLooping Over Lists with Multiple Variables
🤔Before reading on: can you guess how to loop over a list of pairs, like color and size, using @each? Commit to your answer.
Concept: Learn to unpack multiple values from a list of lists inside an @each loop.
You can loop over a list of lists like this: $sizes: (small, 12px), (medium, 16px), (large, 20px); @each $name, $size in $sizes { .text-#{$name} { font-size: $size; } } This creates classes with different font sizes.
Result
Multiple variables can be extracted from each list item to create complex styles.
Knowing how to unpack values expands the power of @each for more detailed styling.
5
AdvancedCombining @each with Nested Selectors
🤔Before reading on: do you think @each can be used inside nested selectors to create complex CSS? Commit to your answer.
Concept: Use @each inside nested selectors to generate styles for child elements dynamically.
Example: $states: normal, hover, active; .button { @each $state in $states { &:#{$state} { color: if($state == hover, blue, black); } } } This creates .button:hover and .button:active styles.
Result
You get dynamic pseudo-class styles generated from a list.
Combining @each with nesting helps write DRY and scalable CSS for interactive states.
6
ExpertPerformance and Limitations of @each Loops
🤔Before reading on: do you think using very large lists in @each loops can affect CSS file size or browser performance? Commit to your answer.
Concept: Understand how large or complex @each loops impact compiled CSS and maintainability.
While @each loops save coding time, very large lists generate big CSS files, which can slow down page loading. Also, deeply nested loops can make debugging harder. Use loops wisely and consider alternatives like CSS custom properties or utility frameworks for very large style sets.
Result
Knowing when to use or avoid @each loops helps balance automation and performance.
Understanding the tradeoffs prevents overusing loops and keeps stylesheets efficient and maintainable.
Under the Hood
When Sass compiles your code, it reads the @each loop and repeats the block inside it for every item in the list. It replaces the loop variable with the current item each time. This happens during compilation, so the browser only sees the final CSS without loops.
Why designed this way?
Sass was designed to make CSS easier to write and maintain. The @each loop was created to automate repetitive tasks in stylesheets, reducing human error and saving time. It compiles to plain CSS because browsers do not understand Sass syntax.
Sass source code with @each loop
        │
        ▼
Compiler reads list and loop
        │
        ▼
Repeats styles for each item
        │
        ▼
Generates plain CSS without loops
        │
        ▼
Browser renders final styles
Myth Busters - 4 Common Misconceptions
Quick: Does @each loop run in the browser or during Sass compilation? Commit to your answer.
Common Belief:Some think @each loops run in the browser like JavaScript loops.
Tap to reveal reality
Reality:@each loops run only during Sass compilation, producing static CSS output.
Why it matters:Believing loops run in the browser leads to confusion about dynamic styling and performance.
Quick: Can you modify the original list inside an @each loop? Commit to your answer.
Common Belief:People often believe you can change the list items inside the loop.
Tap to reveal reality
Reality:Lists are immutable during the loop; you cannot change the original list inside @each.
Why it matters:Trying to modify lists inside loops causes errors or unexpected results.
Quick: Does @each loop automatically create CSS classes if you forget to write selectors? Commit to your answer.
Common Belief:Some think @each automatically generates CSS selectors for list items.
Tap to reveal reality
Reality:You must write selectors explicitly; @each only repeats the block with variables replaced.
Why it matters:Assuming automatic selector creation leads to missing styles and confusion.
Quick: Can you use @each to loop over maps directly like lists? Commit to your answer.
Common Belief:Many believe @each works the same for maps and lists without difference.
Tap to reveal reality
Reality:@each can loop over maps but requires different syntax to unpack keys and values.
Why it matters:Misusing @each with maps causes syntax errors and bugs.
Expert Zone
1
When looping over lists of lists, the number of variables in @each must match the number of items in each sublist exactly, or it causes errors.
2
Using interpolation inside selectors with @each allows dynamic class names but can lead to invalid CSS if not carefully formatted.
3
@each loops do not preserve order if the list is a map converted to a list; understanding this helps avoid unexpected style order.
When NOT to use
Avoid using @each loops for very large lists or deeply nested loops that generate huge CSS files. Instead, consider CSS custom properties, utility-first CSS frameworks, or JavaScript-driven styling for dynamic or large-scale style changes.
Production Patterns
In real projects, @each loops are used to generate theme color classes, responsive utility classes, or state-based styles efficiently. They often combine with variables and functions to create scalable, maintainable design systems.
Connections
JavaScript for loops
Similar pattern of repeating actions for each item in a list.
Understanding how loops work in JavaScript helps grasp the concept of repeating styles in Sass with @each.
Database batch processing
Both process multiple items one by one automatically.
Knowing batch processing in databases clarifies how @each automates repetitive tasks efficiently.
Assembly line manufacturing
Both involve repeating a process for each item in a sequence.
Seeing @each as an assembly line helps understand how automation reduces manual work and errors.
Common Pitfalls
#1Forgetting to use interpolation in selectors inside @each loops.
Wrong approach:@each $color in $colors { .bg-$color { background-color: $color; } }
Correct approach:@each $color in $colors { .bg-#{$color} { background-color: $color; } }
Root cause:Not knowing that Sass requires interpolation (#{$var}) to insert variables into selectors.
#2Trying to modify the list variable inside the @each loop.
Wrong approach:@each $color in $colors { $colors: append($colors, yellow); .bg-#{$color} { background-color: $color; } }
Correct approach:// Define list once outside loop $colors: red, blue, green; @each $color in $colors { .bg-#{$color} { background-color: $color; } }
Root cause:Misunderstanding that Sass variables are immutable inside loops.
#3Using @each loop without a list variable, causing syntax errors.
Wrong approach:@each $item in red, blue, green { .color-#{$item} { color: $item; } }
Correct approach:$colors: red, blue, green; @each $item in $colors { .color-#{$item} { color: $item; } }
Root cause:Not assigning the list to a variable before looping.
Key Takeaways
The @each loop in Sass automates repeating styles for every item in a list, saving time and reducing errors.
Lists are essential to use with @each loops because they hold the items you want to loop over.
Interpolation (#{$variable}) is required to insert variables into selectors inside @each loops.
@each loops run during Sass compilation, producing static CSS that browsers understand.
Using @each loops wisely prevents bloated CSS and keeps stylesheets maintainable and efficient.

Practice

(1/5)
1. What does the @each loop do in Sass when used with a list?
easy
A. It repeats a block of styles for each item in the list.
B. It creates a new list from the original list.
C. It deletes items from the list one by one.
D. It converts the list into a map automatically.

Solution

  1. Step 1: Understand the purpose of @each

    The @each loop is designed to run a block of code for every item in a list.
  2. Step 2: Identify what happens with each item

    For each item, it repeats the styles or code inside the loop, creating multiple style blocks.
  3. Final Answer:

    It repeats a block of styles for each item in the list. -> Option A
  4. Quick Check:

    @each loops = repeat styles [OK]
Hint: Remember: @each repeats code for every list item [OK]
Common Mistakes:
  • Thinking @each modifies the list itself
  • Confusing @each with list functions like map
  • Assuming it deletes or filters items
2. Which of the following is the correct syntax to loop over a list (red, green, blue) using @each in Sass?
easy
A. @each $color in (red, green, blue) { color: $color; }
B. @each color in red, green, blue { color: color; }
C. @each $color from (red, green, blue) { color: $color; }
D. @each $color on (red, green, blue) { color: $color; }

Solution

  1. Step 1: Identify correct @each syntax

    The correct syntax uses @each $variable in (list) to loop over items.
  2. Step 2: Check each option

    @each $color in (red, green, blue) { color: $color; } uses @each $color in (red, green, blue) which is correct. Options A, B, and D use wrong keywords or miss the $ sign.
  3. Final Answer:

    @each $color in (red, green, blue) { color: $color; } -> Option A
  4. Quick Check:

    Use @each $var in (list) syntax [OK]
Hint: Use 'in' keyword and $variable for each item [OK]
Common Mistakes:
  • Omitting the $ before the variable
  • Using wrong keywords like 'from' or 'on'
  • Not wrapping list in parentheses
3. What will be the output CSS of this Sass code?
@each $size in (small, medium, large) {
  .btn-#{$size} {
    font-size: if($size == small, 1rem, if($size == medium, 1.5rem, 2rem));
  }
}
medium
A. Syntax error due to nested if statements
B. .btn-small { font-size: 2rem; } .btn-medium { font-size: 1rem; } .btn-large { font-size: 1.5rem; }
C. .btn-small { font-size: 1rem; } .btn-medium { font-size: 1.5rem; } .btn-large { font-size: 2rem; }
D. .btn-small { font-size: 1.5rem; } .btn-medium { font-size: 2rem; } .btn-large { font-size: 1rem; }

Solution

  1. Step 1: Understand the loop and interpolation

    The loop runs over sizes: small, medium, large. The class name uses interpolation to create .btn-small, .btn-medium, .btn-large.
  2. Step 2: Evaluate the font-size condition

    Using nested if: small -> 1rem, medium -> 1.5rem, large -> 2rem.
  3. Final Answer:

    .btn-small { font-size: 1rem; } .btn-medium { font-size: 1.5rem; } .btn-large { font-size: 2rem; } -> Option C
  4. Quick Check:

    Loop + interpolation + if = correct CSS [OK]
Hint: Match each list item to its style using interpolation [OK]
Common Mistakes:
  • Mixing up font-size values
  • Thinking nested if causes syntax error
  • Ignoring interpolation in class names
4. Identify the error in this Sass code using @each loop:
@each $color (red, green, blue) {
  .text-#{$color} {
    color: $color;
  }
}
medium
A. Variable $color should not have a $ sign.
B. Interpolation syntax #{$color} is incorrect.
C. Parentheses around the list are not allowed.
D. Missing 'in' keyword after $color in the loop.

Solution

  1. Step 1: Check the @each loop syntax

    The correct syntax requires the keyword in between the variable and the list.
  2. Step 2: Identify the missing keyword

    The code misses in after $color, causing a syntax error.
  3. Final Answer:

    Missing 'in' keyword after $color in the loop. -> Option D
  4. Quick Check:

    @each $var in (list) needs 'in' [OK]
Hint: Always write '@each $var in (list)' with 'in' keyword [OK]
Common Mistakes:
  • Forgetting the 'in' keyword
  • Removing $ from variable names
  • Misusing interpolation syntax
5. Given the list (10px, 20px, 0, 30px), how can you use @each to create margin classes but skip the zero value?
hard
A. @each $m in (10px, 20px, 0, 30px) { .m-#{$m} { margin: $m; } }
B. @each $m in (10px, 20px, 0, 30px) { @if $m != 0 { .m-#{$m} { margin: $m; } } }
C. @each $m in (10px, 20px, 0, 30px) { @if $m == 0 { .m-#{$m} { margin: $m; } } }
D. @each $m in (10px, 20px, 0, 30px) { @if $m > 30px { .m-#{$m} { margin: $m; } } }

Solution

  1. Step 1: Loop over all margin values

    The @each loop goes through each value including zero.
  2. Step 2: Use @if to skip zero

    Inside the loop, add @if $m != 0 to only create classes for non-zero margins.
  3. Final Answer:

    @each $m in (10px, 20px, 0, 30px) { @if $m != 0 { .m-#{$m} { margin: $m; } } } -> Option B
  4. Quick Check:

    Use @if inside @each to filter items [OK]
Hint: Use @if inside @each to skip unwanted values [OK]
Common Mistakes:
  • Not filtering zero, so unwanted class is created
  • Using wrong condition like == 0 instead of != 0
  • Trying to filter outside the loop
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