// 在样式顶层生成占位符
@at-root {
%#{$id} {
// 生成共有样式
common: inspect($my-args);
}
}
// 扩展该占位符
@extend %#{$id};
// 生成任意特定的样式
specific: inspect($rest);
}
}
.test {
@include my-mixin(1, 2, (), 4, 5);
}
.test2 {
@include my-mixin(1, 2);
}
.test3 {
@include my-mixin(1, 2, (), 6, 7);
}
生成的 CSS 代码:
CSS Code复制内容到剪贴板
.test {
specific: 4, 5;
}
.test, .test2, .test3 {
common: 1, 2, ();
}
.test2 {
specific: ();
}
.test3 {
specific: 6, 7;
}
混合宏灵活传参的秘技——Null
在 Sass 混合宏中,我们可以向其传递参数列表,便于快速地配置相关属性。就比如下面的这个混合宏,其中就包含了四个参数,用于定义元素的 display,padding 和 margin。
CSS Code复制内容到剪贴板
@mixin display ($disp, $padding, $l-margin, $r-margin) {
display: $disp;
padding: $padding;
margin-left: $l-margin;
margin-right: $r-margin;
}
当我们调用这个混合宏时,必须为每个参数传递一个合理的值,否则就会出现错误提示。
这往往强迫开发者为非必须的变量传值,甚至重置非必要的初始值。那么,怎样才能避免必须为每一个变量传值呢?
混合宏中的可选参数
如果我们为参数提供默认值,那么这个参数就成为了可选参数:










