SASS / SCSS:将类作为父级嵌套,将标记嵌套为子级

时间:2017-03-14 08:42:03

标签: css sass nested

对于指定的类,我需要根据具有该类的标记应用不同的规则。生成的CSS应为:

.class {
    display: block;
}
table.class {
    display: table;
}
tr.class {
    display: table-row;
}
td.class {
    display: table-cell;
}

在我的SCSS中,我尝试过:

.class {
    // ...

    table#{&} {
        // ...
    }
    // etc.
}

...但它编译了这个,这是错误的:

.class {
    // ...
}
.class table.class {
    // ...
}
// etc.

我怎样才能做到这一点?

如果我将&符号放在标记名称之前,那么它会编译为.classtable.class { … },这更糟糕。

1 个答案:

答案 0 :(得分:5)

尝试@at-root

.class {
  display: block;
  @at-root {
    table#{&} {
      display: table;
    }
    tr#{&} {
      display: table-row;
    }
    td#{&} {
      display: table-cell;
    }
  }
}