1

示例代码(我知道可以重写什么以避免级联,但我将其编写为示例。这段代码不是真正的问题,我可以用另一种方式解决,这只是说明):

.b-list {  
  //…

  &__item {
    //…
  }

  &__link {
    height: 4px;
    //…

    @at-root .b-list__item.-active & {
      height: 12px;       
    }     
  }
}

它被编译为:

.b-list__link {
  height: 4px;
}

.b-list__item.-active .b-list__link {
  height: 12px;
}

我想将选择器更改为@at-root .b-list__item.-active &
类似@at-root &__item.-active & {…}
避免重复父类名的东西,但它在 Sass 中不起作用:

此代码不起作用:

.b-list {  
  //…

  &__item {
    //…
  }

  &__link {
    height: 4px;
    //…

    @at-root &__item.-active & {
      height: 12px;       
    }     
  }
}

那么,有办法做我想做的事吗?

4

2 回答 2

3

@at-root有一些方法可以在没有样式功能的情况下实现您正在寻找的代码。但是,由于这是最初的问题,因此以下内容应该可以解决问题。

您可以&稍后通过嵌套将其应用于变量并将其作为类名的一部分进行转义,如下所示:

.b-list {
    $rootParent: &;
    &__link {
        height: 4px;

        #{$rootParent}__item.-active & {
            height: 12px;
        }
    }
}

看起来绝对疯狂,但它的工作原理!

如果您希望以更标准化的方式重新创建上述内容,我肯定会推荐以下内容:

.b-list {
    &__link {
        height: 4px;
    }

    &__item.-active &__link {
        height: 12px;
    }
}

还值得一读http://sass-guidelin.es/#selector-nesting,特别是关于 BEM 命名与&当前选择器参考的部分,其中指出:

虽然这可能是轶事,但从当前选择器引用 (&) 生成新选择器会使这些选择器在代码库中无法搜索,因为它们本身并不存在。

于 2015-07-27T13:51:02.090 回答
0

使用分配了块名称的“根”变量是一种常见的做法,但我发现它不是很优雅,所以构建了一个名为superbem的简单库。这是几个 Sass mixin,可以帮助你以声明的方式坚持 BEM 命名。您的示例如下所示:

@include block(b-list) {
    @include element(link) {
        height: 4px;
    }

    @include element(item) {
        &.-active {
            @include element(link) {
                height: 12px;
            }
        }
    }
}
于 2017-10-16T19:41:05.980 回答