Sass @mixin 和 @include

Sass Mixin

@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;
}

因此,如需包含上面創建的 important-text mixin:

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

Mixins 接受參數。通過這種方式,您可以將變量傳遞給 mixin。

以下是定義帶參數的 mixin 的方法:

SCSS 語法:

/* 定義帶兩個參數的 mixin */
@mixin bordered($color, $width) {
  border: $width solid $color;
}
.myArticle {
  @include bordered(blue, 1px);  // 調用帶兩個值的 mixin
}
.myNotes {
  @include bordered(red, 2px); // 調用帶兩個值的 mixin
}

請注意,參數被設置為變量,然后用作邊框屬性的值(顏色和寬度)。

編譯后,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);
}