## 在指令中延伸
在指令中使用@extend时有一些限制,sass不可以将@media层外的css规则延伸给指令层内的css,这样会生成大量的无用代码。如下面例子是可行的:
``` @media print { .error { border: 1px #f00; background-color: #fdd; } .seriousError { @extend .error; border-width: 3px; } } ```
但不可以这样:
``` .error { border: 1px #f00; background-color: #fdd; } @media print { .seriousError { @extend .error; border-width; 3px; } } ```
# 控制指令
## @if
当@if的表达式返回值不是false或者null时,条件成立,输出{} 内的代码:
``` p { @if 1 + 1 == 2 {border: 1px solid; } @if 5 < 3 {border: 2px dotted;} @if null {border: 3px double;} } ```
编译为
`p { border; 1px solid;}`
与别的语言相同的,也有else if和 if这些这里不过多说明
## @for
这个指令包含两种格式:
`@for $var from <start> through <end>`
`@for $var from <start> to <end>`
``` @for $i from 1 through 3 { .item-#{$i} { width: 2em * $i; } } ```
编译为
``` .item-1 { width: 2em; } .item-2 { width: 4em; } .item-3 { width: 6em; } ```
## @each
遍历数组,@each指令的格式是`$var in <list>`
``` @each $animal in puma, sea-slug, egret, salamander { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); } } ```
## @while
@while指令重复输出格式直到表达式返回结果为false,这样可实现比@for更复杂的循环,只是很少会用到
``` $i: 6; @while $i > 0 { .item-#{$i} { width: 2em * $i; } $i: $i - 2; } ```
# 混合指令
混合指令(mixin)用于定义可重复使用的样式,避免了使用无语意的class
## 定义混合指令
混合指令的用法是在@mixin后添加名称与样式
``` @mixin large-text { font: { family: Arial; size: 20px; weight: bold; } color: #ff0000; } ```
## 引用混合样式@include
使用@include指令引用混合样式,格式是在其后添加混合名称,以及需要的参数
``` .page-title { @include large-text; padding: 4px; margin-top: 10px; } ```
混合样式中也可以包含其他混合样式
``` @mixin compound { @include highlighted-background; @include header-text; } @mixin highlighted-background { background-color: #fc0; } @mixin header-text { font-size: 20px; } ```
## 参数
参数用于给混合指令中的样式设定变量,并且赋值使用
``` @mixin sexy-border($color, $width) { border: { color: $color; width: $width; style: dashed; } } p{ @include sexy-border(blue, lin) } ```
混合指令也可以使用给变量赋值的方法给参数设定默认值,然后,当这个指令被引用的时候,如果没有给参数赋值,则自动使用默认值
``` @mixin sexy-border($color, $width: 1in) { border: { color: $color; width: $width; style: dashed; } } p {@include sexy-border(blue)} h1 {@icnlude sexy-border(blue, 2in)} ```
## 参数变量
如果不能确定混合指令需要使用多少个参数,可以使用参数变量...声明
``` @mixin box-shadow($shadow...) { box-shadow: $shadow; } .shadows { @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999); } ```
编译为
``` .shadowed { box-shadow: 0px 4px 5px #666, 2px 6px 10px #999; } ```
# 函数指令
sass支持自定义函数,并能在任何属性值或者sassscript中使用
``` $grid-width: 40px; $gutter-width: 10px; @function grid-width($n) { @return $n * $grid-width + ($n - 1) * $gutter-width; } #sidebar { width: grid-width(5); } ```