18910140161

HTML-SCSS动态选择器-堆栈溢出

顺晟科技

2022-10-18 13:13:57

35

我有这个SCSS代码:

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

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

@media screen and (max-width: 768px) {
  .row,
  .column,
  .box,
  .box-1,
  .box-2,
  .box-3,
  .box-4,
  .box-5 {
    /* ... */
  }
}

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

谢谢你们!


顺晟科技:

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

编译为:

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

编译为:

<代码>.BOX-1{弹性:008.3333333333%;}.BOX-2{弹性:0016.6666666667%;}[...].框-12{弹性:00100%;}@媒体屏幕和(最大宽度:768px){。row,。column,。box,。box-1,。box-2,[...],。box-11,.框-12{/* ... */}}
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航