首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SCSS动态选择器

SCSS动态选择器
EN

Stack Overflow用户
提问于 2021-09-21 23:48:30
回答 1查看 47关注 0票数 4

我有这个SCSS代码:

代码语言:javascript
复制
$box-length: 12 !default;
@for $i from 1 through $box-length {
  .box-#{$i} {
    flex: 0 0 (100% / $box-length * $i);
  }
}

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

代码语言:javascript
复制
@media screen and (max-width: 768px) {
  .row,
  .column,
  .box,
  .box-1,
  .box-2,
  .box-3,
  .box-4,
  .box-5 {
    /* ... */
  }
}

如何向.row, .column, .box追加动态.box-{num}

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-09-22 05:45:39

1.使用placeholder selector@extend

代码语言:javascript
复制
@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);
  }
}

编译为:

代码语言:javascript
复制
@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

代码语言:javascript
复制
$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;
    }
}

编译为:

代码语言:javascript
复制
.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 {
    /* ... */
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69276700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档