SASS/SCSS @extend规则选择器

ast*_*-7g 16 css sass

我对@extend规则有一点问题,这就是我得到的(专注于h1):

.content-header {
    // CSS properties
    h1 {
        // CSS properties
    }
}

.box-header {
    // CSS properties
    h1 {
        @extend .content-header h1; // My selector problem!
        // And his own CSS properties
    }
}
Run Code Online (Sandbox Code Playgroud)

所以它将是:

.content-header h1, .box-header h1 {
    /* Happily sharing the same CSS properties */
}
Run Code Online (Sandbox Code Playgroud)

但似乎@extend不喜欢这样,是否有任何其他方式来写这个而不给出h1一个类?

o.v*_*.v. 9

嵌套选择器无法扩展 - 实际上,这是解析器报告的语法错误.除了结构性评论(我不能想到上述@extend关系有必要的情况),这不是目前SASS可以完成的事情.

注意:如果您对它开放,可以使用Stylus支持.


Rap*_*sek 6

一个显而易见的解决方案是对子级定义一个新的@mixin your-name为你的.content-header h1定义和@include your-name范围内.box-header h1

但是,有一个更好的解决方案引用父选择器:&

h1 {
    .content-header &,
    .box-header & {
        // CSS properties
    }
    .box-header & {
        // And his own CSS properties
    }
}
Run Code Online (Sandbox Code Playgroud)

这并不明显,因为逻辑相反,但最好维护。您正在更改h1特定选择器的定义。