Scipion
Scipion

Reputation: 11888

Sass: Using for to nest selectors

I have written the following bit in scss to target the siblings with the same class:

    .Foo {
        & ~ .Foo {
            bottom: 2 * $distance-from-bottom + $height;

            & ~ .Foo {
                bottom: 3 * $distance-from-bottom + (2 * $height);

                & ~ .Foo {
                    bottom: 4 * $distance-from-bottom + (3 * $height);

                    & ~ .Foo {
                        bottom: 5 * $distance-from-bottom + (4 * $height);
                    }
                }
            }
        }
    }

I would like to replace it using scss @for. However, I am struggling to see how to have these nested selectors. Any idea ?

Upvotes: 2

Views: 57

Answers (2)

Geoffrey C.
Geoffrey C.

Reputation: 231

It's maybe be an overkill solution but what about something like that?

$sel: '';
@for $i from 1 through 5 {
    $sel: if($i == 1, ".Foo", selector-nest($sel, "& ~ .Foo")) !global;

    if($i > 1) {
        #{$sel} {
            bottom: $i * $distance-from-bottom + ( ( $i - 1 ) * $height);
        }
    }
}

Not tested but that could be a first clue.

Upvotes: 1

Henfs
Henfs

Reputation: 5411

You can make it using append each loop:

$height: 100px;
$distance-from-bottom: 50px;
$var: #{"&"};

@for $i from 2 to 6 {

  .Foo {
    #{append($var, #{"~ &"})} {
      bottom: $i * $distance-from-bottom + ($height*($i - 1));
    }
  }

  $var: append($var, #{"~ &"});
}

Result:

.Foo ~ .Foo {
  bottom: 200px;
}

.Foo ~ .Foo ~ .Foo {
  bottom: 350px;
}

.Foo ~ .Foo ~ .Foo ~ .Foo {
  bottom: 500px;
}

.Foo ~ .Foo ~ .Foo ~ .Foo ~ .Foo {
  bottom: 650px;
}

Upvotes: 1

Related Questions