Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCSS nth-child in for loop? [duplicate]

I was trying to create a loop to create a number of nth-child selectors with matching content:

$show-numbers: true;

@if $show-numbers {
  @for $i from 1 through 5 {
    &:nth-child(1) {
      &:before {
        content: '#{$i}';
      }
    }
  }
}

This, of course, makes 5 copies of

ul.checkout-bar li:nth-child(1):before {
   content: "1";
}

with the "content" correctly incremented. But I cannot get the nth-child value to increment. Is this not possible in Sass?

NOTE a static variable can be interpolated:

$foo: 1;
    &:nth-child(#{$foo}) {
      &:before {
        content: '1';
      }
    }

This works fine. It's the first thing I tried.

However, when using the $i in the for loop, it does not work.

like image 813
Steve Avatar asked Dec 20 '22 05:12

Steve


1 Answers

You need to wrap the $i as an integer in the :nth-child() like this:

$show-numbers: true;

@if $show-numbers {
  @for $i from 1 through 5 {
    &:nth-child(#{$i}) {
      &:before {
        content: '#{$i}';
      }
    }
  }
}

Renders:

:nth-child(1):before {
    content:'1';
}

:nth-child(2):before {
    content:'2';
}

:nth-child(3):before {
    content:'3';
}

:nth-child(4):before {
    content:'4';
}

:nth-child(5):before {
    content:'5';
}
like image 51
codyogden Avatar answered Dec 30 '22 10:12

codyogden