混合器类似于函数,可以包含可重用的样式和变量,简化复杂样式定义。
@mixin 指令允许我们定义一个可以在整个样式表中重复使用的样式。
@include 指令可以将混入(mixin)引入到文档中。
//定义无参数的混合器
@mixin name{
background: #fff;
box-shadow: 0 0 1px rgba(0,0,0,.25);
color: #222;
}
.main{
@include name;//使用默认值
}
//定义有参数混合器,name混合器名称,$theme混合器传参,#f00参数默认值
@mixin name($theme:#f00){
background: $theme;
box-shadow: 0 0 1px rgba($theme, .25);
color: #fff;
}
//使用混合器,使用@include关键字
.info{
@include name;//使用默认值
}
.success {
@include name($theme:#73df8a);//传参
}
//设置可变参数
@mixin box-shadow($shadows...){
-moz-box-shadow: $shadows;
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
//引用
.shadows {
@include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
//浏览器前缀使用混入
@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);
}
注意:Sass 的连接符号 - 与下划线符号 _ 是相同的,也就是 @mixin color-set { } 与 @mixin color_set { } 是一样的混入。
//具体实例设置,定义混合器
@mixin colorSet($bgColor:#fff4e4,$boxColor:#000d8b){
background: $bgColor;
box-shadow: 0 0 10px rgba($boxColor,0.5);
-moz-box-shadow: 0 0 10px rgba($boxColor,0.5);
-webkit-box-shadow: 0 0 10px rgba($boxColor,0.5);
color: #000;
}
//使用混合器
.ceshi-main{
.info{
width: 60px;
height: 60px;
@include colorSet;//使用默认值
}
.info2{
width: 60px;
height: 60px;
@include colorSet(#edfff1,#00470f);//使用默认值
//@include colorSet($bgColor:#edfff1,$boxColor:#00470f);
}
}
//渲染结果
.ceshi-main .info{
width: 60px;
height: 60px;
background: #fff4e4;
box-shadow: 0 0 10px rgba(0, 13, 139, 0.5);
-moz-box-shadow: 0 0 10px rgba(0, 13, 139, 0.5);
-webkit-box-shadow: 0 0 10px rgba(0, 13, 139, 0.5);
color: #000;
}
.ceshi-main .info2{
width: 60px;
height: 60px;
background: #edfff1;
box-shadow: 0 0 10px rgba(0, 71, 15, 0.5);
-moz-box-shadow: 0 0 10px rgba(0, 71, 15, 0.5);
-webkit-box-shadow: 0 0 10px rgba(0, 71, 15, 0.5);
color: #000;
}
混合器也支持嵌套
//定义混合器
@mixin mainText($size:14px,$color:#222,$lightColor:#999){
color: $color;
font-size: $size;
p{
color: $color;
font-size: $size;
}
span{
font-size: 24rpx;
color: $lightColor;
}
}
//使用混合器
.info{
@include mainText;
}
.success{
@include mainText(18rpx, #3bc157, #c6e7cd);
}
.error{
@include mainText(18rpx, #e73535, #eab7b7);
}