Skip to content

Sass - Mixin 指令

Mixins 是 Sass 最强大的特性之一,用于创建可复用的样式块。它们允许你定义一组 CSS 声明,可以在样式表的其他地方包含(include),并可选择性地接受参数进行定制。

你可以使用 @mixin 指令来定义一个 mixin,后面跟着 mixin 名称和一个可选的参数列表。要包含的样式放在花括号 {} 内。

语法:

// 简单 mixin
@mixin mixin-name {
property1: value1;
property2: value2;
}
// 带参数的 mixin
@mixin mixin-name-with-args($arg1, $arg2: default-value) {
property1: $arg1;
property2: $arg2;
// ... 在声明中使用参数
}

示例:一个用于通用按钮样式的 mixin。

@mixin button-base {
display: inline-block;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
text-align: center;
text-decoration: none;
}

示例:一个使用参数创建可主题化按钮的 mixin。

@mixin themed-button($bg-color, $text-color: white) {
@include button-base; // 包含基础样式
background-color: $bg-color;
color: $text-color;
&:hover {
background-color: darken($bg-color, 10%);
}
}

要在 CSS 规则或另一个 mixin 中使用 mixin,你需要使用 @include 指令,后跟 mixin 名称和任何必需的参数。

语法:

.selector {
@include mixin-name;
}
.another-selector {
// 按顺序传递参数
@include mixin-name-with-args(value1, value2);
// 按名称传递参数 (关键字参数)
@include mixin-name-with-args($arg2: value2, $arg1: value1);
}

示例:使用 themed-button mixin。

.button-primary {
@include themed-button(blue);
}
.button-secondary {
@include themed-button(gray, black);
}
.button-danger {
@include themed-button($bg-color: red, $text-color: white);
}

编译后的 CSS 输出:

.button-primary {
display: inline-block;
padding: 10px 20px;
/* ... 其他基础样式 */
background-color: blue;
color: white;
}
.button-primary:hover {
background-color: #0000cc; /* 加深的蓝色 */
}
.button-secondary {
display: inline-block;
padding: 10px 20px;
/* ... 其他基础样式 */
background-color: gray;
color: black;
}
.button-secondary:hover {
background-color: #6b6b6b; /* 加深的灰色 */
}
/* ... .button-danger 的规则 */

Mixins 可以像函数一样接受参数,从而实现定制:

  • 必需参数 (Required Arguments): 在包含 mixin 时必须提供。
  • 可选参数 (Optional Arguments / Default Values): 使用 : 指定默认值 (例如,$arg: default)。在包含时不需要传递。
  • 关键字参数 (Keyword Arguments): 参数可以通过名称传递 (例如,$name: value),这允许以任意顺序传递它们,并使包含更具可读性。
  • 可变参数 (Variable Arguments / ...): mixin 可以使用参数列表末尾的 ... 接受任意数量的参数。这些参数在 mixin 内部作为列表可用。

示例:带有可变参数的 box-shadow mixin。

@mixin box-shadow($shadows...) {
// $shadows 是所有传递参数的列表
box-shadow: $shadows;
}
.element {
@include box-shadow(0 2px 4px rgba(0,0,0,0.1), 0 0 1px rgba(0,0,0,0.05));
}

Mixins 可以使用 @content 指令接受整个样式块。当你包含一个带有内容块的 mixin 时,该块内的样式会被注入到 mixin 定义中出现 @content 的位置。这对于创建包装器或处理媒体查询特别有用。

示例:一个用于响应式样式的 mixin。

@mixin respond-to($breakpoint) {
@media (min-width: $breakpoint) {
@content; // 内容块样式在此处
}
}
.element {
width: 100%;
@include respond-to(768px) {
// 此块作为内容传递
width: 50%;
float: left;
}
}

编译后的 CSS 输出:

.element {
width: 100%;
}
@media (min-width: 768px) {
.element {
width: 50%;
float: left;
}
}

Mixins 非常适合:

  • 减少重复的通用样式模式。
  • 通过参数创建可配置的样式组件。
  • 封装复杂的 CSS,如浏览器前缀(尽管现在更推荐使用 Autoprefixer),特定的 hack 或复杂的选择器。
  • 使用 @content 块处理响应式设计模式。

避免将 mixins 用于简单的属性共享,这种情况下使用 @extend 和占位符选择器(如果关系确实是语义继承)可能更合适,但 mixins 通常更安全且更灵活。