Sass 有兩種副檔名寫法:.sass 有著更嚴格的格式要求,而 .scss 則更貼近原生 CSS。本文將快速瀏覽 Sass 的幾個主要特性。
先看 .sass 的寫法:
#main
color: #fff
&-sidebar
border: 1px solid
它等同於 .scss 的:
#main {
color: black;
&-sidebar { border: 1px solid; }
}
其中代表父元素的 & 只能出現在選擇器開頭,否則無法解析。
.funky {
font: {
family: fantasy;
size: 30em;
weight: bold;
}
}
編譯為:
.funky {
font-family: fantasy;
font-size: 30em;
font-weight: bold;
}
這在一些冗長的 CSS3 屬性(如 animation)上特別實用。
使用 #{} 可將變數插入選擇器或屬性:
$name: foo;
$attr: border;
p.#{$name} {
#{$attr}-color: blue;
}
p {
$font-size: 12px;
$line-height: 30px;
font: #{$font-size}/#{$line-height};
}
第二個例子中,若不加內插,12/30 會被當成除法運算。
p {
width: 1in + 8pt;
}
單位若可轉換,會被自動換算,編譯為:
p {
width: 1.111in;
}
而除法則要看情況而定:
p {
font: 10px/8px; // 純 CSS,不做除法
$width: 1000px;
width: $width/2; // 用了變數,執行除法
width: round(1.5)/2; // 用了函式,執行除法
height: (500px/2); // 用了括號,執行除法
margin-left: 5px + 8px/2px; // 用了 +,執行除法
}
以上編譯為:
p {
font: 10px/8px;
width: 500px;
height: 250px;
margin-left: 9px;
}
p {
color: #010203 + #040506; // RGB 三位分別相加
color: #010203 * 2; // 相乘
color: rgba(255, 0, 0, 0.75) + rgba(0, 255, 0, 0.75); // 帶 alpha 通道的疊加
color: opacify($translucent-red, 0.3); // 降低透明度(加強不透明)
background-color: transparentize($translucent-red, 0.25); // 提高透明度
}
$content: "First content";
$content: "Second content?" !default;
$new_content: "First time reference" !default;
#main {
content: $content;
new-content: $new_content;
}
!default 的規則是:若變數已被賦值,則沿用先前的賦值;若尚未賦值,才採用 !default 後的值。這在撰寫可覆寫的預設樣式時非常實用。