1 函数 function
Sass允许用户编写自己的函数,以 @function 开始,用 @return 返回值。
$fontSize: 10px; @function pxTorem($px) { @return $px / $fontSize * 1rem; } div { font-size: pxTorem(16px); } // css编译后样式 div { font-size: 1.6rem; }
2 条件语句
@if 语句可以用来判断,配套的还有 @else 命令。
// Sass样式 $type: monster; div { @if $type == ocean { color: blue; } @else if $type == matador { color: red; } @else if $type == monster { color: green; } @else { color: black; } } // css编译后样式 div { color: green; }
三目判断:语法为 if($condition, $if_true, $if_false)
三个参数分别表示:条件,条件为真的值,条件为假的值
if(true, 1px, 2px) => 1px if(false, 1px, 2px) => 2px
3 循环语句
3.1 for 循环
有两种形式,分别为:
-
@for $var from <start> through <end>
-
@for $var from <start> to <end>
$var 表示变量,start 表示开始值,end 表示结束值,两种形式的区别在于 through 包括 end 的值,to 不包括 end 值。
// Sass样式 @for $i from 1 to 4 { .item-#{$i} {width: 2em * $i;} } // css编译后样式 .item-1 { width: 2em; } .item-2 { width: 4em; } .item-3 { width: 6em; }
3.2 while 循环
// Sass样式 $i: 2; @while $i > 0 { .item-#{$i} {width: 2em * $i;} $i: $i - 1; } // css编译后样式 .item-2 { width: 4em; } .item-1 { width: 2em; }
3.3 each 循环
语法为 @each $var in <list or map>
。
其中 $var 表示变量,而 list 和 map 表示数据类型
Sass 3.3.0 新加入多字段循环和 map 数据循环
单字段 list 数据循环
//Sass 样式 $animal-list: puma, sea-slug, egret; @each $animal in $animal-list { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); } } //css 编译后样式 .puma-icon { background-image: url('/images/puma.png'); } .sea-slug-icon { background-image: url('/images/sea-slug.png'); } .egret-icon { background-image: url('/images/egret.png'); }
多字段 list 数据循环
//Sass 样式 $animal-data: (puma, black, default),(sea-slug, blue, pointer); @each $animal, $color, $cursor in $animal-data { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); border: 2px solid $color; cursor: $cursor; } } //css 编译后样式 .puma-icon { background-image: url('/images/puma.png'); border: 2px solid black; cursor: default; } .sea-slug-icon { background-image: url('/images/sea-slug.png'); border: 2px solid blue; cursor: pointer; }
多字段 map 数据循环
//Sass 样式 $headings: (h1: 2em, h2: 1.5em, h3: 1.2em); @each $header, $size in $headings { #{$header} { font-size: $size; } } //css 编译后样式 h1 { font-size: 2em; } h2 { font-size: 1.5em; } h3 { font-size: 1.2em; }