編譯
sass的編譯命令:sass input.css output.css
真正使用場(chǎng)景下可以對(duì)整個(gè)文件夾進(jìn)行監(jiān)聽,即時(shí)地進(jìn)行編譯:sass --watch app/sass:public/stylesheets
sass --watch 錯(cuò)誤處理
當(dāng).scss文件中有中文字符時(shí),比如:font-family:"微軟雅黑",執(zhí)行sass --watch或sass input.css output.css可能會(huì)報(bào)error No such file or directory @ rb_sysopen --sass錯(cuò)誤。
找到ruby的安裝目錄下的lib=>ruby=>gems=>2.X.X=>gems=>sass-3.X.X=>lib=>sass文件夾下的engine.rb文件,在所有的require最后加上Encoding.default_external = Encoding.find('utf-8')這段代碼。
變量
sass允許使用變量,以$開頭。
如果變量需要寫在字符串中,就必須要寫在#{}之中
$fontColor : #45fd3e;
$side_left:left;
div.header {
color: $fontColor;
width: 200px;
height: 100px;
border-#{$side_left}-color: red;
border-#{$side_left}-width: 2px;
border-#{$side_left}-style: solid;
}
嵌套
sass允許選擇器嵌套,就像html的DOM結(jié)構(gòu)一樣。
ul {
list-style:none;
li {
height: 30px;
line-height:30px;
}
}
在嵌套的代碼塊內(nèi),可以使用&引用父元素。
a {
text-decoration:none;
&:hover {
color:#43afd2;
}
}
引入(import)
每個(gè)單獨(dú)的scss都是一個(gè)模塊,模塊一般用下劃線開頭來命名。如_base.scss,這樣sass就能識(shí)別出來這是一個(gè)模塊,然后通過@import就可以引入模塊。
// _base.scss
* {
margin:0;
padding:0;
font:normal 16px '微軟雅黑';
color:#333
}
div.header {
color: $fontColor;
width: 200px;
height: 100px;
border-#{$side_left}-color: red;
border-#{$side_left}-width: 2px;
border-#{$side_left}-style: solid;
}
// index.scss
$fontColor : #45fd3e;
$side_left:left;
@import 'base';
ul {
list-style:none;
li {
height: 30px;
line-height:30px;
a {
text-decoration:none;
&:hover {
color:#43afd2;
}
}
}
}
編譯為css之后:
// index.css
@charset "UTF-8";
* {
margin: 0;
padding: 0;
font: normal 16px '微軟雅黑';
color: #333;
}
div.header {
color: #45fd3e;
width: 200px;
height: 100px;
border-left-color: red;
border-left-width: 2px;
border-left-style: solid;
}
div.header {
color: #45fd3e;
width: 200px;
height: 100px;
border-left-color: red;
border-left-width: 2px;
border-left-style: solid;
}
ul {
list-style: none;
}
ul li {
height: 30px;
line-height: 30px;
}
ul li a {
text-decoration: none;
}
ul li a:hover {
color: #43afd2;
}
混合器(mixin)
使用@mixin可以定義一個(gè)代碼塊,這個(gè)代碼塊可以被重用,使用@include可以調(diào)用這個(gè)mixin。mixin可以指定參數(shù)和參數(shù)的缺省值。使用的時(shí)候根據(jù)需要,加入?yún)?shù)。
@mixin border-radius($radius:10px) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}
div.circle {
width: 100px;
height: 100px;
background: #660099;
@include border-radius(50px)
}
繼承(extend)
sass允許一個(gè)選擇器,繼承另一個(gè)選擇器。使用@extend命令。
.father {
height: 30px;
padding:0 10px;
border:1px solid #006699;
}
.son {
@extend .father;
border-color:#884df3;
}
運(yùn)算
sass允許在代碼中使用算式:
div {
width: 50px * 2;
height: (200px/2);
background: #660099;
}
注釋
sass有兩種注釋風(fēng)格。標(biāo)準(zhǔn)的css注釋/* 這是注釋掉的內(nèi)容 */和單行注釋// 這是注釋掉的內(nèi)容,標(biāo)準(zhǔn)的css注釋會(huì)保留到編譯后的文件,單行注釋只保留在scss源文件中,編譯后被省略。
自定義函數(shù)
sass允許用戶編寫自己的函數(shù)
@function double($n){
@return $n * 2;
}
div.sidebar {
width: double(5px);
}