简体   繁体   中英

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 ?

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM