Artvader Artvader - 3 months ago 25
Sass (Sass) Question

How to create a SCSS loop with element+element similar to :nth-child(n) pseudo selector?

Currently I have a SCSS code that loops from 1 to n and applies a property specific to that element. It looks something like this:

@for $i from 1 through 6 {
.element:nth-child(#{$i}n) {
position:absolute;
left:10*$i;
top:5*$i;
}
}


However, I found out that some browsers I'm targeting does not support the nth-child psuedo-element. Therefore, I would like to use the element+element selector.

How do I achieve the same effect as the sample code above that older browsers can understand? Thanks.

Answer

Demo on sassmeister.

Scss code

$selector-name: '.element';
$selector: $selector-name;

@for $i from 1 through 6 {
  #{$selector} {
    position: absolute;
    left: 10 * $i;
    top: 5 * $i;
  }

  $selector: $selector + ' + ' + $selector-name;
}

compiles to

.element {
  position: absolute;
  left: 10;
  top: 5;
}

.element + .element {
  position: absolute;
  left: 20;
  top: 10;
}

.element + .element + .element {
  position: absolute;
  left: 30;
  top: 15;
}

.element + .element + .element + .element {
  position: absolute;
  left: 40;
  top: 20;
}

.element + .element + .element + .element + .element {
  position: absolute;
  left: 50;
  top: 25;
}

.element + .element + .element + .element + .element + .element {
  position: absolute;
  left: 60;
  top: 30;
}

Don't forget to add pixels to left and right properties.

Comments