要在需要类似属性设置的地方扩展名为 .clear-left 的公共代码块,并在扩展时将 .clear-left 附加到选择器(使其更具体或更健壮),您可以使用以下任一选项(首先是最喜欢的,最后是最不喜欢的)。
选项 1: 只需在扩展时将所需的类附加到父选择器即可。这里不需要对通用功能进行额外的更改。这是最简单的解决方案,也是我个人推荐的解决方案。
.clear-left {
> li:first-child {
border-left:none;
margin-left:0;
padding-left:0;
}
}
#footer ul {
&.clear-left:extend(.clear-left all){}; /* appended class while extending */
}
选项 2: 与上面相同,但不是将其作为带括号的 mixin,而是将其包装为 wrapper 选择器的一部分,如下所示。在这里,由于它不完全是用作函数的 mixin,因此可以对其进行扩展,并将选择器分组以避免重复。这种方法比下一种方法好,但它会在输出中产生一个额外的选择器行。
.some-wrapper{
&.clear-left{
> li:first-child {
border-left:none;
margin-left:0;
padding-left:0;
}
}
}
#footer ul:extend(.some-wrapper all){}; /* extend attached to the selector */
#header ul:extend(.some-wrapper all){};
编译输出:
.some-wrapper.clear-left > li:first-child, /* this is the extra selector */
#footer ul.clear-left > li:first-child,
#header ul.clear-left > li:first-child {
border-left: none;
margin-left: 0;
padding-left: 0;
}
选项 3: 将整个通用函数放在一个包装器 mixin 中,以父选择器 (&) 为前缀,并在需要时调用它。由于.clear-left 被附加到父选择器,因此在输出中它总是被附加到调用它的根父选择器(如本例中的.inline-list.clear-left)。这种方法的缺点是可以调用/调用mixin,但不能扩展(意味着选择器不会被分组,属性会一次又一次地重复)。
.some-wrapper() {
&.clear-left{ /* note the use of parent selector (&) */
> li:first-child {
border-left:none;
margin-left:0;
padding-left:0;
}
}
}
.inline-list {
> li {
float:left;
}
.some-wrapper; /* invoke the mixin */
}