学习Sass无非就是想高效的、 面向对象编写CSS,Sass中的Interpolation #{}
就是重要的一部分。开始一探究竟...
SCSS:
@charset "UTF-8"; //不声明在ruby编译时会报错,因为下面有中文注释; $prop1: border; //一个值; @mixin set-one($side, $val){ #{$prop1}-#{$side}: $val; //#{$prop1}-$side: $val; <= 这样写编译会出现错误,记得#{$side}; } .box-bor{ @include set-one(width, 2px); @include set-one(style, dashed); @include set-one(color, green); }
被编译为:
.box-bor { border-width: 2px; border-style: dashed; border-color: green; //咦!不对啊,写border一般不都这样嘛! => border: 2px dashed green; 请看下面 }
border: 2px dashed green;
SCSS:
@mixin set-more($wid, $sty, $col){ #{$prop1}: #{$wid} #{$sty} #{$col}; //其实就是结合混合宏传多个参数; } .box-bor2{ @include set-more(2px, dashed , green); }
被编译为:
.box-bor2 { border: 2px dashed green; }
@each
多个值操作 SCSS:
$prop2: (padding, margin); //多个值用括号; @mixin set-prop($side, $val){ @each $prop in $prop2{ //遍历$prop2里的所有值(margin,padding) #{$prop}-#{$side}: $val; //注意'-'前后不能有空格; } } .box{ @include set-prop(left, 16px); }
被编译为:
.box { padding-left: 16px; margin-left: 16px; }
用过bootstrap的都知道,它的button有个预定义样式,现在我也来试试:
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-danger">Danger</button>
SCSS:
@mixin selector($c, $s, $i, $w, $d, $sc, $ic, $wc, $dc){ .#{$c}-success{ background-color: $s; border-color:$sc; } .#{$c}-info { background-color: $i; border-color:$ic; } .#{$c}-warning{ background-color: $w; border-color:$wc; } .#{$c}-danger { background-color: $d; border-color:$dc; } } //@include selector('btn', #5cb85c, #5bc0de, #f0ad4e, #d9534f, //background-color #4cae4c, #46b8da, #eea236, #d43f3a); //border-color //$c可(可不)带单双引号,上面代码换行为了好方便阅读,当然编译的时候也是能正常编译的; //直接@include selector调用编译后是没有.btn; .btn{ color: #fff; @include selector(btn, #5cb85c, #5bc0de, #f0ad4e, #d9534f, #4cae4c, #46b8da, #eea236, #d43f3a); }
被编译为:
.btn { color: #fff; } .btn .btn-success { background-color: #5cb85c; border-color: #4cae4c; } .btn .btn-info { background-color: #5bc0de; border-color: #46b8da; } .btn .btn-warning { background-color: #f0ad4e; border-color: #eea236; } .btn .btn-danger { background-color: #d9534f; border-color: #d43f3a; }
刚刚构建了一个选择器,可能会让你想到超级mixins,用来生成另一个mixins。这可能限制很擅长使用Sass变量的插值(Interpolation)。看下面的代码:
SCSS:
$btn-success: #5cb85c; $btn-info: #5bc0de; $btn-warning: #f0ad4e; $btn-danger: #d9534f; @mixin set-bg($name) { background-color: $btn-#{$name};//btn有多种状态,都存在变量里; } .btn { @include set-bg(success); }
上面的代码的写法,编译会报错:
(Line 52: Undefined variable: "$btn-".)
@mixin btn-status { margin-top: 20px; background: #F00; } $flag: "status"; .box { @include btn-#{$flag}; }
也会报错:
(Line 64: Invalid CSS after "...nclude updated -": expected "}", was "#{$flag};")
SCSS:
%btn-status { //不能像mixin那样传参了! margin-top: 20px; background: #F00; } $flag: "status"; .foo { @extend %btn-#{$flag}; }
被编译为:
.foo { margin-top: 20px; background: #F00; }