SASS / SCSS For Loop

Posted by: Alex on June 30, 2013

Looking to have an incrementing list or numbered :nth-child‘s in your CSS, but don’t want to type it out manually?

Using a SCSS for loop will save you a huge amount of time, instead of manually typing out these kind of situations. Obviously, if you’re using this too much there’s possibly something to look at with your approach, but for things like :nth-child‘s where you may want each one to be different it’s very good.

Use the following to create nth-child styles from 1 to 20.

@for $i from 1 through 20 {
  span:nth-child(#{$i}) {
    // your Styles here
  }
}

After compiling you get:

span:nth-child(1) {
  // Your Styles here
}

span:nth-child(2) {
  // Your Styles here
}

span:nth-child(3) {
  // Your Styles here
}

span:nth-child(4) {
  // Your Styles here
}

span:nth-child(5) {
  // Your Styles here
}

span:nth-child(6) {
  // Your Styles here
}

span:nth-child(7) {
  // Your Styles here
}

span:nth-child(8) {
  // Your Styles here
}

span:nth-child(9) {
  // Your Styles here
}

span:nth-child(10) {
  // Your Styles here
}

span:nth-child(11) {
  // Your Styles here
}

span:nth-child(12) {
  // Your Styles here
}

span:nth-child(13) {
  // Your Styles here
}

span:nth-child(14) {
  // Your Styles here
}

span:nth-child(15) {
  // Your Styles here
}

span:nth-child(16) {
  // Your Styles here
}

span:nth-child(17) {
  // Your Styles here
}

span:nth-child(18) {
  // Your Styles here
}

span:nth-child(19) {
  // Your Styles here
}

span:nth-child(20) {
  // Your Styles here
}