混合指令用于定义可重复使用的样式 ,避免了使用无语意的 class(然后延伸继承),可以通过传入参数来输出多样化的样式 。
1 . 定义混合指令 : @mixin
用法 : 在 @mixin 后添加名称与样式 ,如下:
@ mixin my-text {
font : {
family : Arial ;
size : 20px ;
weight : 700
}
color : #ff0000
& : hover{
weight : 400
}
}
2 . 引用混合样式 : @include
用法 : 在 @include 后加上定义的混合指令即可引用
.box-text{
@ include my-text ;
padding : 4px ;
}
// 也可以在最外层直接引用 ,此时不能使用父选择器。
混合样式中也可以包含其他混合样式 ,如下 :
@mixin compound {
@include highlighted-background;
@include header-text;
}
3 . 参数 :
参数用于给混合指令中的样式设定变量,并且赋值使用。在定义混合指令的时候,按照变量的格式,通过逗号分隔,将参数写进圆括号里。引用指令时,按照参数的顺序,再将所赋的值对应写进括号。
@ mixin my-box($height , $width , &bgc){
height : $height ;
width : $width ;
background-color : $bgc ;
}
.top{
@ include my-box(50px , 400px , pink)
}
可以使用给变量赋值的方法给参数设定默认值,然后,当这个指令被引用的时候,如果没有给参数赋值,则自动使用默认值。
@ mixin my-box($height , $width , `&bgc :red` ){
height : $height ;
width : $width ;
background-color : $bgc ;
}
.top{
@ include my-box(50px , 400px)
}
4 . 关键词参数 :
可以通过关键词法传参 。虽然不够简明 ,但阅读方便 ,且传参顺序可以改变 。
@ mixin my-box($height , $width , &bgc ){
height : $height ;
width : $width ;
background-color : $bgc ;
}
.top{
@ include my-box( $height :50px , $width : 400px , bgc : red)
}
5 . 向定义好的混合样式中导入内容 :
定义时,在要导入的地方 ,写上 @content ; 引用时额外的代码就会放在该地方。
@ mixin my-html{
* html{
@ content;
}
}
@include my-html{
# logo{
background-color : red;
}
}
// 编译后就是
* html #logo{
background-color : red;
}