Sass @mixin 및 @include

Sass Mixin

@mixin 지시는 전체 웹사이트에서 반복적으로 사용할 수 있는 CSS 코드를 생성할 수 있도록 합니다.

생성 @include 지시는 mixin을 사용하거나(참조)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);
}