CSS預(yù)處理器Sass詳解
Sass 是一款強(qiáng)化 CSS 的輔助工具,它在 CSS 語法的基礎(chǔ)上增加了變量 (variables)、嵌套 (nested rules)、混合 (mixins)、導(dǎo)入 (inline imports) 等高級(jí)功能,這些拓展令 CSS 更加強(qiáng)大與優(yōu)雅。使用 Sass 以及 Sass 的樣式庫(kù)(如 Compass)有助于更好地組織管理樣式文件,以及更高效地開發(fā)項(xiàng)目。
1. 特色功能
- 完全兼容 CSS3
- 在 CSS 基礎(chǔ)上增加變量、嵌套 (nesting)、混合 (mixins) 等功能
- 通過函數(shù)進(jìn)行顏色值與屬性值的運(yùn)算
- 提供控制指令 (control directives)等高級(jí)功能
- 自定義輸出格式
文件后綴名稱:sass有兩種后綴名文件,一種后綴名為sass,不使用大括號(hào)和分號(hào);另一種就是我們這里使用的scss文件,這種和我們平時(shí)寫的css文件格式差不多,使用大括號(hào)和分號(hào)。而本教程中所說的所有sass文件都指后綴名為scss的文件。在此也建議使用后綴名為scss的文件,以避免sass后綴名的嚴(yán)格格式要求報(bào)錯(cuò)。
//文件后綴名為sass的語法
body
background: #eee
font-size:12px
p
background: #0982c1
//文件后綴名為scss的語法
body {
background: #eee;
font-size:12px;
}
p{
background: #0982c1;
}
2. Sass、Less語法比較
2.1 Sass與Less不同之處
- 編譯環(huán)境不一樣——Sass基于Ruby等服務(wù)器端環(huán)境編譯,Less既可以支持服務(wù)器端編譯也可在客戶端(瀏覽器環(huán)境)編譯
- 變量符不一樣——Sass使用$符號(hào)聲明變量,Less使用@符號(hào)聲明變量
- 對(duì)于條件語句的支持不一樣——Sass支持復(fù)雜的條件語句(類似于if..else..),Less僅支持簡(jiǎn)單的條件語句(類似于if()..)
- 作用域——Sass局部修改變量可影響全局變量,Less則只會(huì)在局部作用域生效。
- 引用外部CSS文件方式不同——Sass默認(rèn)引入.sass或.scss文件時(shí)可忽略后綴,Less則需要通過關(guān)鍵字配置來控制引入文件如何處理。
2.2 Sass與Less相似的地方
- 混入(Mixins)——類似于函數(shù)或者宏,并且可以傳遞參數(shù);
- 嵌套規(guī)則——class中嵌套class,從而減少重復(fù)的代碼;
- 運(yùn)算——CSS中運(yùn)用加減乘除計(jì)算各種數(shù)值以及字符串等;
- 顏色功能——可以通過內(nèi)置函數(shù)編輯顏色;
- 命名空間(namespace)——分組樣式,從而可以被調(diào)用;
3. Sass語法主要功能介紹
3.1 CSS功能擴(kuò)展
嵌套規(guī)則
Sass 允許將一套 CSS 樣式嵌套進(jìn)另一套樣式中,內(nèi)層的樣式將它外層的選擇器作為父選擇器,嵌套功能避免了重復(fù)輸入父選擇器,而且令復(fù)雜的 CSS 結(jié)構(gòu)更易于管理,例如:
//sass style or less style
#main p {
color: #00ff00;
width: 97%;
.redbox {
background-color: #ff0000;
color: #000000;
}
}
//css style
#main p {
color: #00ff00;
width: 97%; }
#main p .redbox {
background-color: #ff0000;
color: #000000; }
父選擇器 &
在嵌套 CSS 規(guī)則時(shí),有時(shí)也需要直接使用嵌套外層的父選擇器,例如,當(dāng)給某個(gè)元素設(shè)定 hover 樣式時(shí),或者當(dāng) body 元素有某個(gè) classname 時(shí),可以用 & 代表嵌套規(guī)則外層的父選擇器。
//sass style or less style
a {
font-weight: bold;
text-decoration: none;
&:hover { text-decoration: underline; }
body.firefox & { font-weight: normal; }
}
//css style
a {
font-weight: bold;
text-decoration: none; }
a:hover {
text-decoration: underline; }
body.firefox a {
font-weight: normal; }
屬性嵌套
有些 CSS 屬性遵循相同的命名空間 (namespace),比如 font-family, font-size, font-weight 都以 font 作為屬性的命名空間。為了便于管理這樣的屬性,同時(shí)也為了避免了重復(fù)輸入,Sass 允許將屬性嵌套在命名空間中,例如:
//sass style
.funky {
font: {
family: fantasy;
size: 30em;
weight: bold;
}
}
//css style
.funky {
font-family: fantasy;
font-size: 30em;
font-weight: bold; }
命名空間也可以包含自己的屬性值,例如:
//sass style
.funky {
font: 20px/24px {
family: fantasy;
weight: bold;
}
}
//css style
.funky {
font: 20px/24px;
font-family: fantasy;
font-weight: bold; }
3.2導(dǎo)入
sass的導(dǎo)入(@import)規(guī)則和CSS的有所不同,編譯時(shí)會(huì)將@import的scss文件合并進(jìn)來只生成一個(gè)CSS文件。但是如果你在sass文件中導(dǎo)入css文件如 @import ‘reset.css’,那效果跟普通CSS導(dǎo)入樣式文件一樣,導(dǎo)入的css文件不會(huì)合并到編譯后的文件中,而是以 @import 方式存在。
所有的sass導(dǎo)入文件都可以忽略后綴名.scss。一般來說基礎(chǔ)的文件命名方法以_開頭,如_mixin.scss。這種文件在導(dǎo)入的時(shí)候可以不寫下劃線,可寫成@import “mixin”。
less的導(dǎo)入(@import)語法:@import (keyword) “filename”;
多個(gè)關(guān)鍵字 @import 是允許的,你必須使用逗號(hào)分隔關(guān)鍵字:example: @import (optional, reference) “foo.less”;
- reference: 使用該less文件但是不輸出它
- inline: 包括在源文件中輸出,但是不作處理
- less: 將該文件視為less文件,無論其擴(kuò)展名為什么
- css: 將文件視為css文件,無論擴(kuò)展名為什么
- once: 該文件僅可導(dǎo)入一次 (默認(rèn))
- multiple: 該文件可以多次導(dǎo)入
- optional: 當(dāng)沒有發(fā)現(xiàn)文件時(shí)仍然編譯
導(dǎo)入文件代碼示例:
/*被導(dǎo)入sass文件a.scss,less文件a.less:*/
//a.scss or a.less
//-------------------------------
body {
background: #eee;
}
/*需要導(dǎo)入樣式的sass文件b.scss,less文件b.less:*/
@import "reset.css";
@import "a";
p{
background: #0982c1;
}
/*轉(zhuǎn)譯出來的b.css樣式:*/
@import "reset.css";
body {
background: #eee;
}
p{
background: #0982c1;
}
根據(jù)上面的代碼可以看出,b.scss編譯后,reset.css繼續(xù)保持import的方式,而a.scss則被整合進(jìn)來了。同理,less中也是這樣處理的。
3.3 注釋 /* */ 與 //
Sass 支持標(biāo)準(zhǔn)的 CSS 多行注釋 /* */,以及單行注釋 //,前者會(huì)被完整輸出到編譯后的 CSS 文件中,而后者則不會(huì)。Less中不用擔(dān)心這一點(diǎn),Less中多行注釋 /* */,以及單行注釋 //都可以隨意使用,都會(huì)在編譯過程中被保留。例如:
//sass style
/* This comment is
* several lines long.
* since it uses the CSS comment syntax,
* it will appear in the CSS output. */
body { color: black; }
// These comments are only one line long each.
// They won't appear in the CSS output,
// since they use the single-line comment syntax.
a { color: green; }
//css style
/* This comment is
* several lines long.
* since it uses the CSS comment syntax,
* it will appear in the CSS output. */
body {
color: black; }
a {
color: green; }
3.4 SassScript
變量 $
Sass的變量必須是$開頭,后面緊跟變量名,如果值后面加上!default則表示默認(rèn)值。Less的變量與Sass類似,只是使用符號(hào)不同,Less中采用的是@
//sass style
//-------------------------------
$fontSize: 12px;
body{
font-size:$fontSize;
}
//less style
//-------------------------------
@fontSize: 12px;
body{
font-size:@fontSize;
}
//css style
//-------------------------------
body{
font-size:12px;
}
變量默認(rèn)值
sass的默認(rèn)變量一般是用來設(shè)置默認(rèn)值,然后根據(jù)需求來覆蓋的,覆蓋的方式也很簡(jiǎn)單,只需要在使用默認(rèn)變量之前重新聲明下變量即可;默認(rèn)變量的價(jià)值在進(jìn)行組件化開發(fā)的時(shí)候會(huì)非常有用。
//sass style
//-------------------------------
$baseLineHeight: 1.5 !default;
body{
line-height: $baseLineHeight;
}
//css style
//-------------------------------
body{
line-height:1.5;
}
/*覆蓋默認(rèn)值*/
//sass style
//-------------------------------
$baseLineHeight: 2;
$baseLineHeight: 1.5 !default;
body{
line-height: $baseLineHeight;
}
//css style
//-------------------------------
body{
line-height:2;
}
變量 #{} 的使用形式
一般我們定義的變量都為屬性值,可直接使用,但是如果變量作為屬性或在某些特殊情況下等則必須要以#{$variables}形式使用。
//sass style
//-------------------------------
$borderDirection: top !default;
$baseFontSize: 12px !default;
$baseLineHeight: 1.5 !default;
//應(yīng)用于class和屬性
.border-#{$borderDirection}{
border-#{$borderDirection}:1px solid #ccc;
}
//應(yīng)用于復(fù)雜的屬性值
body{
font:#{$baseFontSize}/#{$baseLineHeight};
}
//css style
//-------------------------------
.border-top{
border-top:1px solid #ccc;
}
body {
font: 12px/1.5;
}
多值變量 list
簡(jiǎn)單來說list類型有點(diǎn)像js中的數(shù)組。list數(shù)據(jù)可通過空格,逗號(hào)或小括號(hào)分隔多個(gè)值,可用nth($var,$index)取值。
關(guān)于list數(shù)據(jù)操作還有很多其他函數(shù)如length($list),join($list1,$list2,[$separator]),append($list,$value,[$separator])等
定義:
//一維數(shù)據(jù) $px: 5px 10px 20px 30px; //二維數(shù)據(jù),相當(dāng)于js中的二維數(shù)組 $px: 5px 10px, 20px 30px; $px: (5px 10px) (20px 30px);
使用方法:
//sass style
//-------------------------------
$linkColor: #08c #333 !default;//第一個(gè)值為默認(rèn)值,第二個(gè)鼠標(biāo)滑過值
a{
color:nth($linkColor,1);
&:hover{
color:nth($linkColor,2);
}
}
//css style
//-------------------------------
a{
color:#08c;
}
a:hover{
color:#333;
}
多值變量 map
簡(jiǎn)單來說map類型有點(diǎn)像es6語法中的map數(shù)據(jù)結(jié)構(gòu)。map數(shù)據(jù)以key和value成對(duì)出現(xiàn),其中value又可以是list。
格式為:$map: (key1: value1, key2: value2, key3: value3);可通過map-get($map,$key)取值。關(guān)于map數(shù)據(jù)還有很多其他函數(shù)如map-merge($map1,$map2),map-keys($map),map-values($map)等
定義:
$heading: (h1: 2em, h2: 1.5em, h3: 1.2em);
使用方法:
//sass style
//-------------------------------
$headings: (h1: 2em, h2: 1.5em, h3: 1.2em);
@each $header, $size in $headings {
#{$header} {
font-size: $size;
}
}
//css style
//-------------------------------
h1 {
font-size: 2em;
}
h2 {
font-size: 1.5em;
}
h3 {
font-size: 1.2em;
}
變量作用域
Sass和Less中的變量作用域分別類似與javascript中的兩種變量申明方式,下面一段代碼可以對(duì)比出變量聲明時(shí)的不同處理方式。
Sass中的變量賦值直接修改全局變量,Less中的變量賦值可只在局部生效。
//Sass style
$color:red;
p{
$color:blue;
color:$color;//blue
}
a{
color:$color;//blue
}
//Less style
@color:red;
p{
@color:blue;
color:@color;//blue
}
a{
color:@color;//red
}
3.5 混合(mixin)
sass中使用@mixin聲明混合,可以傳遞參數(shù),也可以給參數(shù)設(shè)置默認(rèn)值。聲明的@mixin通過@include來調(diào)用;在less中只需要將定義好的class用類似函數(shù)的方式直接引用。
無參數(shù) mixin
//sass style
@mixin center-block {
margin-left:auto;
margin-right:auto;
}
.demo{
@include center-block;
}
//less style
.center-block {
margin-left:auto;
margin-right:auto;
}
.demo{
.center-block;
}
//css style
.demo{
margin-left:auto;
margin-right:auto;
}
有參數(shù) mixin
//sass style
@mixin opacity($opacity:50) {
opacity: $opacity / 100;
filter: alpha(opacity=$opacity);
}
.opacity-80{
@include opacity(80); //傳遞參數(shù)
}
//less style
.opacity(@opacity:50) {
opacity: @opacity / 100;
filter: alpha(opacity=@opacity);
}
.opacity-80{
.opacity(80); //傳遞參數(shù)
}
//css style
.opacity-80{
opacity: .8;
filter: alpha(opacity=80);
}
多個(gè)參數(shù) mixin
Sass調(diào)用時(shí)可直接傳入值,如@include傳入?yún)?shù)的個(gè)數(shù)小于@mixin定義參數(shù)的個(gè)數(shù),則按照順序表示,后面不足的使用默認(rèn)值,如不足的沒有默認(rèn)值則報(bào)錯(cuò)。除此之外還可以選擇性的傳入?yún)?shù),使用參數(shù)名與值同時(shí)傳入;Less中使用方法類似。
//sass style
@mixin horizontal-line($border:1px dashed #ccc, $padding:10px){
border-bottom:$border;
padding-top:$padding;
padding-bottom:$padding;
}
.imgtext-h li{
@include horizontal-line(1px solid #ccc);
}
//less style
.horizontal-line(@border:1px dashed #ccc, @padding:10px){
border-bottom:@border;
padding-top:@padding;
padding-bottom:@padding;
}
.imgtext-h li{
.horizontal-line(1px solid #ccc);
}
//css style
.imgtext-h li {
border-bottom: 1px solid #cccccc;
padding-top: 10px;
padding-bottom: 10px;
}
多組值參數(shù) mixin
Sass中如果一個(gè)參數(shù)可以有多組值,如box-shadow、transition等,那么參數(shù)則需要在變量后加三個(gè)點(diǎn)表示,如$variables…;Less表示不定參數(shù)時(shí)可以直接使用 … 表示,并用@arguments表示所有參數(shù)
//sass style
//box-shadow可以有多組值,所以在變量參數(shù)后面添加...
@mixin box-shadow($shadow...) {
-webkit-box-shadow:$shadow;
box-shadow:$shadow;
}
.box{
border:1px solid #ccc;
@include box-shadow(0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3));
}
//less style
.box-shadow(...) {
-webkit-box-shadow:@arguments;
box-shadow:@arguments;
}
.box{
border:1px solid #ccc;
.box-shadow(0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3));
}
//css style
.box{
border:1px solid #ccc;
-webkit-box-shadow:0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3);
box-shadow:0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3);
}
3.6 運(yùn)算
sass具有運(yùn)算的特性,可以對(duì)數(shù)值型的Value(如:數(shù)字、顏色、變量、字符串等)進(jìn)行加減乘除四則運(yùn)算。請(qǐng)注意運(yùn)算符前后請(qǐng)留一個(gè)空格,不然會(huì)出錯(cuò)。
//計(jì)算數(shù)值、變量
$baseFontSize: 14px !default;
$baseLineHeight: 2 !default;
$baseGap: $baseFontSize * $baseLineHeight !default; // => 28px
$halfBaseGap: $baseGap / 4 !default; // => 7px
$samllFontSize: $baseFontSize - 2px !default; // => 12px
$_columns: 12 !default;
$_column-width: 60px !default;
$_gutter: 20px !default;
$_gridsystem-width: $_columns * ($_column-width + $_gutter); // => 960px
//計(jì)算顏色
p {
color: #010203 + #040506; // => #050709
}
//計(jì)算字符串
p:before {
content: "Foo " + Bar; // => "Foo Bar"
font-family: sans- + "serif"; // => sans-serif
}
3.7 控制指令
SassScript 提供了一些基礎(chǔ)的控制指令,比如在滿足一定條件時(shí)引用樣式,或者設(shè)定范圍重復(fù)輸出格式??刂浦噶钍且环N高級(jí)功能,日常編寫過程中并不常用到,主要與混合指令 (mixin) 配合使用。
@if
//sass style
p {
@if 1 + 1 == 2 { border: 1px solid; }
@if 5 < 3 { border: 2px dotted; }
@if null { border: 3px double; }
}
//css style
p {
border: 1px solid; }
//sass style
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else if $type == monster {
color: green;
} @else {
color: black;
}
}
//less style
@type: monster;
p (@type) when (@type = ocean){color: blue;}
p (@type) when (@type = matador){color: red;}
p (@type) when (@type = monster){color: green;}
p (@type) when (@type = dark){color: black;}
//css style
p {
color: green; }
@for
@for 指令包含兩種格式:@for $var from <start> through <end>,或者 @for $var from <start> to <end>,區(qū)別在于 through 與 to 的含義:當(dāng)使用 through 時(shí),條件范圍包含 <start> 與 <end> 的值,而使用 to 時(shí)條件范圍只包含 <start> 的值不包含 <end> 的值。另外,$var 可以是任何變量,比如 $i;<start> 和 <end> 必須是整數(shù)值。
//sass style
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
//css style
.item-1 {
width: 2em; }
.item-2 {
width: 4em; }
.item-3 {
width: 6em; }
@each
語法為:@each $var in <list or map>。其中$var表示變量,而list和map表示list類型數(shù)據(jù)和map類型數(shù)據(jù)。
單個(gè)字段list數(shù)據(jù)循環(huán):
//sass style
$animal-list: puma, sea-slug, egret, salamander;
@each $animal in $animal-list {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
//css style
.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');
}
.salamander-icon {
background-image: url('/images/salamander.png');
}
多個(gè)字段list數(shù)據(jù)循環(huán):
//sass style
//-------------------------------
$animal-data: (puma, black, default),(sea-slug, blue, pointer),(egret, white, move);
@each $animal, $color, $cursor in $animal-data {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
border: 2px solid $color;
cursor: $cursor;
}
}
//css style
//-------------------------------
.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;
}
.egret-icon {
background-image: url('/images/egret.png');
border: 2px solid white;
cursor: move;
}
多個(gè)字段map數(shù)據(jù)循環(huán):
//sass style
//-------------------------------
$headings: (h1: 2em, h2: 1.5em, h3: 1.2em);
@each $header, $size in $headings {
#{$header} {
font-size: $size;
}
}
//css style
//-------------------------------
h1 {
font-size: 2em;
}
h2 {
font-size: 1.5em;
}
h3 {
font-size: 1.2em;
}
@extend
@extend 的作用是將重復(fù)使用的樣式 (.error) 延伸 (extend) 給需要包含這個(gè)樣式的特殊樣式(.seriousError),例子:
//sass style
//-------------------------------
.error {
border: 1px #f00;
background-color: #fdd;
}
.error.intrusion {
background-image: url("/image/hacked.png");
}
.seriousError {
@extend .error;
border-width: 3px;
}
//css style
//-------------------------------
.error, .seriousError {
border: 1px #f00;
background-color: #fdd; }
.error.intrusion, .seriousError.intrusion {
background-image: url("/image/hacked.png"); }
.seriousError {
border-width: 3px; }
3.8 函數(shù)指令
Sass 支持自定義函數(shù),并能在任何屬性值或 Sass script 中使用:
//sass style
//-------------------------------
$grid-width: 40px;
$gutter-width: 10px;
@function grid-width($n) {
@return $n * $grid-width + ($n - 1) * $gutter-width;
}
#sidebar { width: grid-width(5); }
//css style
//-------------------------------
#sidebar {
width: 240px; }
與 mixin 相同,也可以傳遞若干個(gè)全局變量給函數(shù)作為參數(shù)。一個(gè)函數(shù)可以含有多條語句,需要調(diào)用 @return 輸出結(jié)果。
Sass 函數(shù)允許使用關(guān)鍵詞參數(shù),上面的例子也可以寫成:
//關(guān)鍵詞參數(shù)調(diào)用形式
#sidebar { width: grid-width($n: 5); }
雖然不夠簡(jiǎn)明,但是閱讀起來會(huì)更方便。關(guān)鍵詞參數(shù)給函數(shù)提供了更靈活的接口,以及容易調(diào)用的參數(shù)。關(guān)鍵詞參數(shù)可以打亂順序使用,如果使用默認(rèn)值也可以省缺,另外,參數(shù)名被視為變量名,下劃線、短橫線可以互換使用。
參考文獻(xiàn):Sass中文文檔 — https://www.sass.hk/docs/
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
- 這篇文章主要介紹了利用CSS的Sass預(yù)處理器來制作居中效果的教程,圍繞Sass mixin的編寫方法進(jìn)行講解,同時(shí)介紹了如何使用Flexbox來讓子元素居中,需要的朋友可以參考下2016-03-10
學(xué)習(xí)CSS預(yù)處理器:Sass和less進(jìn)行對(duì)比
Css可以讓你做很多事情,但它畢竟是給瀏覽器認(rèn)的東西,對(duì)開發(fā)者來說,Css缺乏很多特性2012-07-11

