Dan Prince
Dan Prince

Reputation: 30009

SASS Nested While Loops

Having a problem with the following code, I expect it to generate a CSS file with 9 classes, one for each combination of $x and $y.

$grid-width: 3;
$grid-height: 3;
$x: 0;
$y: 0;

@while $x < $grid-width {
  @while $y < $grid-height {

    .x#{$x}y#{$y} {
      top: $width * $x;
      left: $width * $y;
    }

    $y: $y + 1;
  }

  $x: $x + 1;
}

Instead it generates just one iteration of $y values, almost as though $x was set to 1.

.x0y0 {
  top: 0px;
  left: 0px; }

.x0y1 {
  top: 0px;
  left: 100px; }

.x0y2 {
  top: 0px;
  left: 200px; }

Any ideas?

EDIT I've managed to solve the problem by moving the inner loop into a mixin and including that instead, but it feels messy and I still don't understand why it would work to begin with.

Upvotes: 1

Views: 579

Answers (3)

Imran Bughio
Imran Bughio

Reputation: 4941

Here is the fixed code

$grid-width: 3;
$grid-height: 3;
$x: 0;
$y: 0;
$width: 100;

@while $x < $grid-height {
    @while $y < $grid-height {
        .x#{$x}y#{$y} {
            top: $width * $x;
            left: $width * $y;
        }
        $y: $y + 1;
    }
    $y: 0;
    $x: $x + 1;
}

1) Variable Width was not defined. 2) $y Variable value needs to be reset to keep it less then grid-height so that inner while loop runs each time $x loops run.

Upvotes: 0

Chip
Chip

Reputation: 241

I have zero idea why it fails the outer loop, silly computer, but this seems to do your bidding:

Sass:

$width: 100px;
$height: 100px;

$grid-width: 3;
$grid-height: 3;

@for $i from 0 to $grid-width {
  @for $j from 0 to $grid-height {
    .x#{$i}y#{$j} {
      top: $width * $i;
      left: $width * $j;
    }
  }
}

CSS:

.x0y0 {
  top: 0px;
  left: 0px;
}

.x0y1 {
  top: 0px;
  left: 100px;
}

.x0y2 {
  top: 0px;
  left: 200px;
}

.x1y0 {
  top: 100px;
  left: 0px;
}

.x1y1 {
  top: 100px;
  left: 100px;
}

.x1y2 {
  top: 100px;
  left: 200px;
}

.x2y0 {
  top: 200px;
  left: 0px;
}

.x2y1 {
  top: 200px;
  left: 100px;
}

.x2y2 {
  top: 200px;
  left: 200px;
}

Upvotes: 9

Saxeen
Saxeen

Reputation: 360

Since it is never reset, the $y-value is going to be stuck at the value of three after it has created the first three classes. When the first loop then increases the $x-value to 1 the $y is already at 3 and will therefore never run your second loop to create more classes.

Set the value of $y back to 0 on the row before the one where you increase the value of $x, that should fix things, if I have read your example correctly.

Upvotes: 2

Related Questions