CSS預處理器Sass詳解
Sass 是一款強化 CSS 的輔助工具,它在 CSS 語法的基礎上增加了變量 (variables)、嵌套 (nested rules)、混合 (mixins)、導入 (inline imports) 等高級功能,這些拓展令 CSS 更加強大與優(yōu)雅。使用 Sass 以及 Sass 的樣式庫(如 Compass)有助于更好地組織管理樣式文件,以及更高效地開發(fā)項目。
1. 特色功能
- 完全兼容 CSS3
- 在 CSS 基礎上增加變量、嵌套 (nesting)、混合 (mixins) 等功能
- 通過函數(shù)進行顏色值與屬性值的運算
- 提供控制指令 (control directives)等高級功能
- 自定義輸出格式
文件后綴名稱:sass有兩種后綴名文件,一種后綴名為sass,不使用大括號和分號;另一種就是我們這里使用的scss文件,這種和我們平時寫的css文件格式差不多,使用大括號和分號。而本教程中所說的所有sass文件都指后綴名為scss的文件。在此也建議使用后綴名為scss的文件,以避免sass后綴名的嚴格格式要求報錯。
//文件后綴名為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等服務器端環(huán)境編譯,Less既可以支持服務器端編譯也可在客戶端(瀏覽器環(huán)境)編譯
- 變量符不一樣——Sass使用$符號聲明變量,Less使用@符號聲明變量
- 對于條件語句的支持不一樣——Sass支持復雜的條件語句(類似于if..else..),Less僅支持簡單的條件語句(類似于if()..)
- 作用域——Sass局部修改變量可影響全局變量,Less則只會在局部作用域生效。
- 引用外部CSS文件方式不同——Sass默認引入.sass或.scss文件時可忽略后綴,Less則需要通過關鍵字配置來控制引入文件如何處理。
2.2 Sass與Less相似的地方
- 混入(Mixins)——類似于函數(shù)或者宏,并且可以傳遞參數(shù);
- 嵌套規(guī)則——class中嵌套class,從而減少重復的代碼;
- 運算——CSS中運用加減乘除計算各種數(shù)值以及字符串等;
- 顏色功能——可以通過內(nèi)置函數(shù)編輯顏色;
- 命名空間(namespace)——分組樣式,從而可以被調(diào)用;
3. Sass語法主要功能介紹
3.1 CSS功能擴展
嵌套規(guī)則
Sass 允許將一套 CSS 樣式嵌套進另一套樣式中,內(nèi)層的樣式將它外層的選擇器作為父選擇器,嵌套功能避免了重復輸入父選擇器,而且令復雜的 CSS 結(jié)構更易于管理,例如:
//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ī)則時,有時也需要直接使用嵌套外層的父選擇器,例如,當給某個元素設定 hover 樣式時,或者當 body 元素有某個 classname 時,可以用 & 代表嵌套規(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 作為屬性的命名空間。為了便于管理這樣的屬性,同時也為了避免了重復輸入,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導入
sass的導入(@import)規(guī)則和CSS的有所不同,編譯時會將@import的scss文件合并進來只生成一個CSS文件。但是如果你在sass文件中導入css文件如 @import ‘reset.css’,那效果跟普通CSS導入樣式文件一樣,導入的css文件不會合并到編譯后的文件中,而是以 @import 方式存在。
所有的sass導入文件都可以忽略后綴名.scss。一般來說基礎的文件命名方法以_開頭,如_mixin.scss。這種文件在導入的時候可以不寫下劃線,可寫成@import “mixin”。
less的導入(@import)語法:@import (keyword) “filename”;
多個關鍵字 @import 是允許的,你必須使用逗號分隔關鍵字:example: @import (optional, reference) “foo.less”;
- reference: 使用該less文件但是不輸出它
- inline: 包括在源文件中輸出,但是不作處理
- less: 將該文件視為less文件,無論其擴展名為什么
- css: 將文件視為css文件,無論擴展名為什么
- once: 該文件僅可導入一次 (默認)
- multiple: 該文件可以多次導入
- optional: 當沒有發(fā)現(xiàn)文件時仍然編譯
導入文件代碼示例:
/*被導入sass文件a.scss,less文件a.less:*/
//a.scss or a.less
//-------------------------------
body {
background: #eee;
}
/*需要導入樣式的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則被整合進來了。同理,less中也是這樣處理的。
3.3 注釋 /* */ 與 //
Sass 支持標準的 CSS 多行注釋 /* */,以及單行注釋 //,前者會被完整輸出到編譯后的 CSS 文件中,而后者則不會。Less中不用擔心這一點,Less中多行注釋 /* */,以及單行注釋 //都可以隨意使用,都會在編譯過程中被保留。例如:
//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則表示默認值。Less的變量與Sass類似,只是使用符號不同,Less中采用的是@
//sass style
//-------------------------------
$fontSize: 12px;
body{
font-size:$fontSize;
}
//less style
//-------------------------------
@fontSize: 12px;
body{
font-size:@fontSize;
}
//css style
//-------------------------------
body{
font-size:12px;
}
變量默認值
sass的默認變量一般是用來設置默認值,然后根據(jù)需求來覆蓋的,覆蓋的方式也很簡單,只需要在使用默認變量之前重新聲明下變量即可;默認變量的價值在進行組件化開發(fā)的時候會非常有用。
//sass style
//-------------------------------
$baseLineHeight: 1.5 !default;
body{
line-height: $baseLineHeight;
}
//css style
//-------------------------------
body{
line-height:1.5;
}
/*覆蓋默認值*/
//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;
//應用于class和屬性
.border-#{$borderDirection}{
border-#{$borderDirection}:1px solid #ccc;
}
//應用于復雜的屬性值
body{
font:#{$baseFontSize}/#{$baseLineHeight};
}
//css style
//-------------------------------
.border-top{
border-top:1px solid #ccc;
}
body {
font: 12px/1.5;
}
多值變量 list
簡單來說list類型有點像js中的數(shù)組。list數(shù)據(jù)可通過空格,逗號或小括號分隔多個值,可用nth($var,$index)取值。
關于list數(shù)據(jù)操作還有很多其他函數(shù)如length($list),join($list1,$list2,[$separator]),append($list,$value,[$separator])等
定義:
//一維數(shù)據(jù) $px: 5px 10px 20px 30px; //二維數(shù)據(jù),相當于js中的二維數(shù)組 $px: 5px 10px, 20px 30px; $px: (5px 10px) (20px 30px);
使用方法:
//sass style
//-------------------------------
$linkColor: #08c #333 !default;//第一個值為默認值,第二個鼠標滑過值
a{
color:nth($linkColor,1);
&:hover{
color:nth($linkColor,2);
}
}
//css style
//-------------------------------
a{
color:#08c;
}
a:hover{
color:#333;
}
多值變量 map
簡單來說map類型有點像es6語法中的map數(shù)據(jù)結(jié)構。map數(shù)據(jù)以key和value成對出現(xiàn),其中value又可以是list。
格式為:$map: (key1: value1, key2: value2, key3: value3);可通過map-get($map,$key)取值。關于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中的兩種變量申明方式,下面一段代碼可以對比出變量聲明時的不同處理方式。
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ù)設置默認值。聲明的@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);
}
多個參數(shù) mixin
Sass調(diào)用時可直接傳入值,如@include傳入?yún)?shù)的個數(shù)小于@mixin定義參數(shù)的個數(shù),則按照順序表示,后面不足的使用默認值,如不足的沒有默認值則報錯。除此之外還可以選擇性的傳入?yún)?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中如果一個參數(shù)可以有多組值,如box-shadow、transition等,那么參數(shù)則需要在變量后加三個點表示,如$variables…;Less表示不定參數(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 運算
sass具有運算的特性,可以對數(shù)值型的Value(如:數(shù)字、顏色、變量、字符串等)進行加減乘除四則運算。請注意運算符前后請留一個空格,不然會出錯。
//計算數(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
//計算顏色
p {
color: #010203 + #040506; // => #050709
}
//計算字符串
p:before {
content: "Foo " + Bar; // => "Foo Bar"
font-family: sans- + "serif"; // => sans-serif
}
3.7 控制指令
SassScript 提供了一些基礎的控制指令,比如在滿足一定條件時引用樣式,或者設定范圍重復輸出格式??刂浦噶钍且环N高級功能,日常編寫過程中并不常用到,主要與混合指令 (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 的含義:當使用 through 時,條件范圍包含 <start> 與 <end> 的值,而使用 to 時條件范圍只包含 <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ù)。
單個字段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');
}
多個字段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;
}
多個字段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 的作用是將重復使用的樣式 (.error) 延伸 (extend) 給需要包含這個樣式的特殊樣式(.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 相同,也可以傳遞若干個全局變量給函數(shù)作為參數(shù)。一個函數(shù)可以含有多條語句,需要調(diào)用 @return 輸出結(jié)果。
Sass 函數(shù)允許使用關鍵詞參數(shù),上面的例子也可以寫成:
//關鍵詞參數(shù)調(diào)用形式
#sidebar { width: grid-width($n: 5); }
雖然不夠簡明,但是閱讀起來會更方便。關鍵詞參數(shù)給函數(shù)提供了更靈活的接口,以及容易調(diào)用的參數(shù)。關鍵詞參數(shù)可以打亂順序使用,如果使用默認值也可以省缺,另外,參數(shù)名被視為變量名,下劃線、短橫線可以互換使用。
參考文獻:Sass中文文檔 — https://www.sass.hk/docs/
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
- 這篇文章主要介紹了利用CSS的Sass預處理器來制作居中效果的教程,圍繞Sass mixin的編寫方法進行講解,同時介紹了如何使用Flexbox來讓子元素居中,需要的朋友可以參考下2016-03-10
- Css可以讓你做很多事情,但它畢竟是給瀏覽器認的東西,對開發(fā)者來說,Css缺乏很多特性2012-07-11

