1
\$\begingroup\$

I've finally written my first loop in SCSS, trying to avoid it for quite some time since I thought it was unnecessary (was writing vanilla CSS not so long ago, so I was used to manual work).

However, I feel this code isn't very optimized, especially since I seem to need two different while-loops (one for divs from center to left, and one for divs to the right).

Demo is available at http://codepen.io/pestbarn/pen/myqvEq

The loops

I found myself needing an @if condition for tweaking the margin for the center div by just 1vh.

// generate 6 circles from center to left
$i: 6;
$s: 38;
$t: -19;
$l: -90;
$z: 2;
@while $i > 0 {
  &:nth-child(#{$i}) {
    @include sqsize($s);
    margin-top: $t+vh;
    margin-left: $l+vh;
    z-index: $z;
  }
  $i: $i - 1;
  $s: $s - 2;
  $t: $t + 1;
  @if $l == -30 {
    $l: $l + 16
  } @else {
    $l: $l + 15;
  }
  $z: $z + 1;
}
// generate 5 circles to the right
$i: 11;
$s: 38;
$t: -19;
$l: 52;
$z: 2;
@while $i > 6 {
  &:nth-child(#{$i}) {
    @include sqsize($s);
    margin-top: $t+vh;
    margin-left: $l+vh;
    z-index: $z;
  }
  $i: $i - 1;
  $s: $s - 2;
  $t: $t + 1;
  $l: $l - 13;
  $z: $z + 1;
}

Is there perhaps a way of only needing to write one while-loop for this? From left to right, the div sizes (where 1 is smallest and 6 is largest) go 6 5 4 3 2 1 2 3 4 5 6, in that order.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I ended up rewriting it like this - much more compact and clean. If there are further ways to optimize this, I'm open to suggestions!

// generate circles from left to right

$i: 1; $s: 38; $t: -19; $l: -89.3; $z: 2;

@while $i <= 11 {
    &:nth-child(#{$i}) { 
        @include sqsize($s);
        margin-top: $t+vh;
        margin-left: $l+vh;
        z-index: $z;
    }
    $i: $i + 1;
    $z: $z + 1;
    $b: $i <= 6;
    $l: if($b, $l + 15, $l + 13);
        // <= 6 - circles are coming from the left
        // > 6 - circles are going to the right
    $s: if($b, $s - 2, $s + 2);
        // same logic as above - decrease size towards middle
        // and increase size after passing the middle
    $t: if($b, $t + 1, $t - 1);
        // —〃—
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.