使用@ at-root和&在选择器列表中

时间:2016-04-27 23:57:06

标签: sass

我有一个CSS我尝试使用许多结构(例如

)转移到SASS
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
...
}

有了这个:

 .btn-primary {
    ...
    &:hover,
    &:focus,
    &:active,
    &.active,
    .open .dropdown-toggle#{&} {

我显然得到了:

.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.btn-primary .open .dropdown-toggle.btn-primary {
...
}

但我似乎不允许使用@ at-root:

 .btn-primary {
    ...
    &:hover,
    &:focus,
    &:active,
    &.active,
    @at-root .open .dropdown-toggle#{&} {

因为SASS需要逗号后面的选择器并获得@ ...

1 个答案:

答案 0 :(得分:3)

@at-root指令不能以这种方式使用。它旨在应用完整选择器,而不是列表中的单个选择器。由于您的选择器都是类,您可以将父选择器重新定位到开头,而不是尝试将其追加到最后:

.btn-primary {
    &:hover,
    &:focus,
    &:active,
    &.active,
    .open &.dropdown-toggle {
      color: red;
    }
}

输出:

.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .btn-primary.dropdown-toggle {
  color: red;
}

如果绝对必须在最后(例如,您使用元素或伪选择器),最简单的解决方案是使用extends:

%common {
    color: red;
}

.btn-primary {
    &:hover,
    &:focus,
    &:active,
    &.active {
        @extend %common;
    }

    @at-root .open .dropdown-toggle#{&} {
        @extend %common;
    }
}

输出:

.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary {
  color: red;
}