Sass @mixin 和 @include


Sass 混合

这个@mixin指令允许您创建可在整个网站中重复使用的 CSS 代码。

这个@include创建指令是为了让您使用(包含)mixin。


定义一个 Mixin

mixin 定义为@mixin指示。

Sass @mixin 语法:

@mixin name {
  property: value;
  property: value;
  ...
}

以下示例创建一个名为 "important-text" 的 mixin:

SCSS 语法:

@mixin important-text {
  color: red;
  font-size: 25px;
  font-weight: bold;
  border: 1px solid blue;
}

提示:关于 Sass 中连字符和下划线的提示:连字符和下划线被认为是相同的。这意味着 @mixin important-text { } 和 @mixin important_text { } 被视为相同的 mixin!


使用 Mixin

这个@include指令用于包含 mixin。

Sass @include mixin 语法:

selector {
  @include mixin-name;
}

因此,要包含上面创建的重要文本混合:

SCSS 语法:

.danger {
  @include important-text;
  background-color: green;
}

Sass 转译器会将以上内容转换为普通 CSS:

CSS 输出:

.danger {
  color: red;
  font-size: 25px;
  font-weight: bold;
  border: 1px solid blue;
  background-color: green;
}

运行示例 »

mixin 还可以包含其他 mixin:

SCSS 语法:

@mixin special-text {
  @include important-text;
  @include link;
  @include special-border;
}



将变量传递给 Mixin

Mixin 接受参数。这样你就可以将变量传递给 mixin。

以下是如何使用参数定义 mixin:

SCSS 语法:

/* Define mixin with two arguments */
@mixin bordered($color, $width) {
  border: $width solid $color;
}

.myArticle {
  @include bordered(blue, 1px);  // Call mixin with two values
}

.myNotes {
  @include bordered(red, 2px); // Call mixin with two values
}

请注意,参数被设置为变量,然后用作边框属性的值(颜色和宽度)。

编译后,CSS 将如下所示:

CSS 输出:

.myArticle {
  border: 1px solid blue;
}

.myNotes {
  border: 2px solid red;
}

运行示例 »


Mixin 的默认值

还可以为 mixin 变量定义默认值:

SCSS 语法:

@mixin bordered($color: blue, $width: 1px) {
  border: $width solid $color;
}

然后,您只需要指定包含 mixin 时会更改的值:

SCSS 语法:

.myTips {
  @include bordered($color: orange);
}


使用 Mixin 作为供应商前缀

mixin 的另一个好用途是供应商前缀。

这是一个转换的例子:

SCSS 语法:

@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}

.myBox {
  @include transform(rotate(20deg));
}

编译后,CSS 将如下所示:

CSS 输出:

.myBox {
  -webkit-transform: rotate(20deg);
  -ms-transform: rotate(20deg);
  transform: rotate(20deg);
}