SCSS 动态选择器

Nat*_*les 5 html css sass

我有这个 SCSS 代码:

$box-length: 12 !default;
@for $i from 1 through $box-length {
  .box-#{$i} {
    flex: 0 0 (100% / $box-length * $i);
  }
}
Run Code Online (Sandbox Code Playgroud)

下面,我需要.box-{num}使用其他选择器添加生成的类。要得到这样的 CSS 结果:

$box-length: 12 !default;
@for $i from 1 through $box-length {
  .box-#{$i} {
    flex: 0 0 (100% / $box-length * $i);
  }
}
Run Code Online (Sandbox Code Playgroud)

如何将动态.box-{num}类附加到.row, .column, .box

谢谢你!

Ark*_*lys 2

1. 使用占位符选择器@extend

@media screen and (max-width: 768px) {
    %mq-768 {
        /* ... */
    }
}

.row,
.column,
.box {
  @extend %mq-768;
}

$box-length: 12 !default;
@for $i from 1 through $box-length {
  .box-#{$i} {
    @extend %mq-768;
    flex: 0 0 (100% / $box-length * $i);
  }
}
Run Code Online (Sandbox Code Playgroud)

编译为:

@media screen and (max-width: 768px) {
  .box-12,
  .box-11,
  [...],
  .box-2,
  .box-1,
  .row,
  .column,
  .box {
    /* ... */
  }
}

.box-1 {
  flex: 0 0 8.3333333333%;
}

.box-2 {
  flex: 0 0 16.6666666667%;
}

[...]

.box-12 {
  flex: 0 0 100%;
}
Run Code Online (Sandbox Code Playgroud)

2. 使用变量来存储选择器 和append

$selectors: ".row, .column, .box";

$box-length: 12 !default;
@for $i from 1 through $box-length {
    $boxSelector: ".box-#{$i}" ;
    $selectors: append($selectors, $boxSelector, $separator: comma);
    
  #{$boxSelector} {
    flex: 0 0 (100% / $box-length * $i);
  }
}

@media screen and (max-width: 768px) {
    #{$selectors} {
        color: blue;
    }
}
Run Code Online (Sandbox Code Playgroud)

编译为:

.box-1 {
  flex: 0 0 8.3333333333%;
}

.box-2 {
  flex: 0 0 16.6666666667%;
}

[...]

.box-12 {
  flex: 0 0 100%;
}

@media screen and (max-width: 768px) {
  .row,
  .column,
  .box,
  .box-1,
  .box-2,
  [...],
  .box-11,
  .box-12 {
    /* ... */
  }
}
Run Code Online (Sandbox Code Playgroud)