sass-mixin

mixin的不足: 不能将相同的样式代码块合并在一起。

定义:

1
2
3
@mixin border-radius{
border-radius: 3px;
}

调用:

1
2
3
4
5
6
7
8
.box {
@include border-radius;
margin-bottom: 5px;
}

.btn {
@include border-radius;
}

编译:

1
2
3
4
5
6
7
.box {
border-radius: 3px;
margin-bottom: 5px;
}
.btn {
border-radius: 3px;
}

合并更好

1
2
3
.btn,box{
border-radius: 3px;
}

你可能不知道的“剩余参数”:…

1
2
3
4
5
6
7
8
9
10
11
12
@mixin box-shadow($shadow...) {
-webkit-box-shadow: $shadow;
-moz-box-shadow: $shadow;
box-shadow: $shadow;
}
.shadow1{
@include box-shadow(0 0 5px rgba(0,0,0,.3));
}

.shadow2 {
@include box-shadow(0 0 5px rgba(0,0,0,.3), inset 0 0 3px rgba(255,255,255,.5));
}

mixin的神来之笔: 用@each解决浏览器前缀问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$prefix-for-webkit: true !default;
$prefix-for-mozilla: true !default;
$prefix-for-microsoft: true !default;
$prefix-for-opera: true !default;
$prefix-for-spec: true !default;

@mixin prefixer ($property, $value, $prefixes) {
@each $prefix in $prefixes {
@if $prefix == webkit and $prefix-for-webkit == true {
-webkit-#{$property}: $value;
}
@else if $prefix == moz and $prefix-for-mozilla == true {
-moz-#{$property}: $value;
}
@else if $prefix == ms and $prefix-for-microsoft == true {
-ms-#{$property}: $value;
}
@else if $prefix == o and $prefix-for-opera == true {
-o-#{$property}: $value;
}
@else if $prefix == spec and $prefix-for-spec == true {
#{$property}: $value; } @else { @warn "Unrecognized prefix: #{$prefix}"; }
}
}

@mixin box-shadow($shadow...) {
@include prefixer(box-shadow, $shadow, webkit spec);
}