变量以$开头,既可以用于选择器(Selector),也可以用于属性(Property)和属性值(Value)。
当用于属性值时,通常可以直接引用;当用于选择器、属性和某些复杂属性值(e.g. font-size/line-height
)时,使用 #{$var}
的形式引用。
//简单变量
$bgColor: #fefefe;
$fontSize: 14px;
$lineHeight: 1.5;
html, body {
font: #{$fontSize}/#{lineHeight} sans-serif;
background-color: $bgColor;
}
此处的font-size和line-height两个属性需要以#{$var}的形式引用,否则会被当做除法运算处理。
对于多值变量,有List和Map两种形式,分别类似于JS中的数组和对象,使用方式如下:
//多值变量:List形式
$margins: 5px 10px, 15px 20px;
div {
margin: nth($margins, 1) nth($margins, 2);
padding: nth($margins, 1);
}
//多值变量:Map形式
$headers: (h1:2em, h2:1.5em, h3:1.2em);
@each $header, $size in $headers {
#{$header} {
font-size: $size;
}
}
嵌套可以分为选择器嵌套和属性嵌套,使用 & 表示在嵌套中对父元素的引用。
ul {
border: 1px solid $ul-border-color;
li {
border: 1px solid $li-border-color;
a {
text-decoration: none;
&:hover {
text-decoration: underline;
font: {
size: 1.5em;
weight: bold;
}
}
}
}
}
可传递参数,通常与 @include
配合使用,提高代码复用率。
@mixin round($deg) {
border-radius: $deg;
}
.panel {
@include round(5px);
}
@mixin link-style($selector) {
.list1 #{$selector} {
color: $link-color1;
}
.list2 #{$selector} {
color: $link-color2;
}
}
@include link-style(".link");
当某一类元素拥有大量相同属性时,可以通过继承来简化代码,提高代码复用率。
.btn {
display: inline-block;
margin: 10px;
padding: 5px 15px;
}
.btn-bor {
border: 1px solid #ccc;
}
.btn-red {
@extend .btn;
@extend .btn-bor;
border-color: red;
}
另外,继承可以与占位选择器(%foo)配合使用。
.container div%box {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.bor-box {
@extend %box;
}
//编译为:
.container div.bor-box {...}
SASS内置了颜色、数字等函数,并支持四则运算及分支、遍历等特性,同时允许自定义函数。
$baseFontSize: 14px;
$gray: #ccc;
@function pxToRem($px) {
@return $px / $baseFontSize * 1rem;
}
.dark {
font-size: $baseFontSize;
color: darken($gray, 20%);
}
.light {
font-size: pxToRem(18px);
color: lighten($gray, 20%);
}
SASS支持 //
形式的单行注释及 /* */
形式的多行注释,但是在编译成css文件的时候,单行注释会被丢弃,而多行注释则被保留。