Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS Sass Basics (retired) Advanced Sass Concepts Creating Loops with @for and @each

Creating loops with @for and @each

I'm having a challenge with this task

Make a @for loop to iterate through the numbers 1 through 3. The for loop should create classes named in the format "item_#{$i}" and set the width to be $i * 100px.

1 Answer

Tim Knight
Tim Knight
28,888 Points

Sylvia,

Let's look at the basic structure of a Sass for loop.

It starts with the index ($i) and then provides the range. So you'll have something like this:

@for $i from 1 through 3 {

}

Now if you're wanting to create class you'd use interpolation to create those class names within the loop.

@for $i from 1 through 3 {
  .item_#{$i} {...}
}

Note that I'm using a . before that because I'm addressing it as a class, just like regular CSS. The $i here would be 1, 2, and the 3 (since I told it the range is 1 through 3). #{} is the interpolation syntax we use to allow the index to be put into the class as a string.

And finally, the math.

@for $i from 1 through 3 {
  .item_#{$i} { width: $i * 100px; }
}