@mixin 指令可让您创建可在整个网站中重复使用的 CSS 代码。
创建 @include 指令是为了让您使用(引用)mixin。
mixin 是用 @mixin 指令定义的。
@mixin name {
property: value;
property: value;
...
}
下例创建名为 "important-text" 的 mixin:
@mixin important-text {
color: red;
font-size: 25px;
font-weight: bold;
border: 1px solid blue;
}
关于 Sass 中连字符和下划线的提示:连字符和下划线被认为是相同的。
这意味着 @mixin important-text { } 和 @mixin important_text { } 被认为是同一个 mixin!
@include 指令用于引用 mixin。
selector {
@include mixin-name;
}
因此,如需包含上面创建的 important-text mixin:
.danger {
@include important-text;
background-color: green;
}
Sass 转译器会将上述代码转换为普通 CSS:
.danger {
color: red;
font-size: 25px;
font-weight: bold;
border: 1px solid blue;
background-color: green;
}
mixin 还可以包含其他 mixin:
@mixin special-text {
@include important-text;
@include link;
@include special-border;
}
Mixins 接受参数。通过这种方式,您可以将变量传递给 mixin。
以下是定义带参数的 mixin 的方法:
/* 定义带两个参数的 mixin */
@mixin bordered($color, $width) {
border: $width solid $color;
}
.myArticle {
@include bordered(blue, 1px); // 调用带两个值的 mixin
}
.myNotes {
@include bordered(red, 2px); // 调用带两个值的 mixin
}
请注意,参数被设置为变量,然后用作边框属性的值(颜色和宽度)。
编译后,CSS 将如下:
.myArticle {
border: 1px solid blue;
}
.myNotes {
border: 2px solid red;
}
也可以为 mixin 变量定义默认值:
@mixin bordered($color: blue, $width: 1px) {
border: $width solid $color;
}
然后,您只需要指定引用 mixin 时要更改的值:
.myTips {
@include bordered($color: orange);
}
mixin 的另一个很好的用途是(浏览器)供应商前缀。
这是一个转换的例子:
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
.myBox {
@include transform(rotate(20deg));
}
编译后,CSS 将如下所示:
.myBox {
-webkit-transform: rotate(20deg);
-ms-transform: rotate(20deg);
transform: rotate(20deg);
}
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77万人学习
共29课时
61.7万人学习
共25课时
39.3万人学习
共43课时
70.9万人学习
共25课时
61.6万人学习
共22课时
23万人学习
共28课时
33.9万人学习
共89课时
125万人学习