柚子快報激活碼778899分享:rust Sass學(xué)習(xí)記錄
柚子快報激活碼778899分享:rust Sass學(xué)習(xí)記錄
Sass學(xué)習(xí)記錄
Sass 是一款強(qiáng)化 CSS 的輔助工具,它在 CSS 語法的基礎(chǔ)上增加了變量 (variables)、嵌套 (nested rules)、混合 (mixins)、導(dǎo)入 (inline imports) 等高級功能,這些拓展令 CSS 更加強(qiáng)大與優(yōu)雅。使用 Sass 以及 Sass 的樣式庫(如 Compass)有助于更好地組織管理樣式文件,以及更高效地開發(fā)項目。
1. 特色功能 (Features)
完全兼容 CSS3在 CSS 基礎(chǔ)上增加變量、嵌套 (nesting)、混合 (mixins) 等功能通過函數(shù)進(jìn)行顏色值與屬性值的運(yùn)算提供控制指令 (control directives)等高級功能自定義輸出格式
2. 語法格式 (Syntax)
Sass 有兩種語法格式。首先是 SCSS (Sassy CSS) —— 也是本文示例所使用的格式 —— 這種格式僅在 CSS3 語法的基礎(chǔ)上進(jìn)行拓展,所有 CSS3 語法在 SCSS 中都是通用的,同時加入 Sass 的特色功能。此外,SCSS 也支持大多數(shù) CSS hacks 寫法以及瀏覽器前綴寫法 (vendor-specific syntax),以及早期的 IE 濾鏡寫法。這種格式以 .scss 作為拓展名。
另一種也是最早的 Sass 語法格式,被稱為縮進(jìn)格式 (Indented Sass) 通常簡稱 “Sass”,是一種簡化格式。它使用 “縮進(jìn)” 代替 “花括號” 表示屬性屬于某個選擇器,用 “換行” 代替 “分號” 分隔屬性,很多人認(rèn)為這樣做比 SCSS 更容易閱讀,書寫也更快速。縮進(jìn)格式也可以使用 Sass 的全部功能,只是與 SCSS 相比個別地方采取了不同的表達(dá)方式,具體請查看 the indented syntax reference。這種格式以 .sass 作為拓展名。
任何一種格式可以直接 導(dǎo)入 (@import) 到另一種格式中使用,或者通過 sass-convert 命令行工具轉(zhuǎn)換成另一種格式:
# Convert Sass to SCSS
$ sass-convert style.sass style.scss
# Convert SCSS to Sass
$ sass-convert style.scss style.sass
3. 使用 Sass (Using Sass)
Sass 可以通過以下三種方式使用:作為命令行工具;作為獨立的 Ruby 模塊 (Ruby module);或者作為 Rack-enabled 框架的插件(例如 Ruby on Rails 與 Merb)。無論哪種方式都需要先安裝 Sass gem (Windows 系統(tǒng)需要先安裝 Ruby):
gem install sass
在命令行中運(yùn)行 Sass:
sass input.scss output.css
監(jiān)視單個 Sass 文件,每次修改并保存時自動編譯:
sass --watch input.scss:output.css
監(jiān)視整個文件夾:
sass --watch app/sass:public/stylesheets
更多命令的用法請通過 sass --help 獲取幫助。
在 Ruby 中使用 Sass 也非常容易,Sass gem 安裝完畢后運(yùn)行 require "sass" 然后按照下面的方法使用 Sass::Engine:
engine = Sass::Engine.new("#main {background-color: #0000ff}", :syntax => :scss)
engine.render #=> "#main { background-color: #0000ff; }\n"
3.1. Rack/Rails/Merb Plugin
在 Rails 3 之前的版本中使用 Sass,需要在 environment.rb 文件中添加:
config.gem "sass"
Rails 3 則需要在 Gemfile 中添加:
gem "sass"
在 Merb 中使用 Sass,需要在 config/dependencies.rb 中添加:
dependency "merb-haml"
在 Rack 中使用 Sass,需要在 config.ru 中添加:
require 'sass/plugin/rack'
use Sass::Plugin::Rack
樣式文件與 views 不同,不包含任何動態(tài)內(nèi)容,因此 CSS 只需要在 Sass 文件被修改后再編譯生成。默認(rèn)情況下 .sass 與 .scss 文件放置在 public/stylesheets/sass 中(可通過 :template_location 修改路徑),編譯生成的 CSS 文件放置在 public/stylesheets 中。例如 public/stylesheets/sass/main.scss 編譯生成 public/stylesheets/main.css。
3.2. 緩存 (Caching)
Sass 自動緩存編譯后的模板與 partials,這樣做能夠顯著提升重新編譯的速度,尤其在處理由 @import 導(dǎo)入多個子文件的大型項目時。
單獨使用 Sass,緩存內(nèi)容保存在 .sass-cache 文件夾中。在 Rails 和 Merb 項目中緩存文件保存在 tmp/sass-cache 文件夾中(可通過 :cache_location 修改路徑)。禁用緩存可將 :cache 設(shè)為 false。
3.3. 配置選項 (Options)
暫未翻譯
3.4. 判斷語法格式 (Syntax Selection)
Sass 命令行工具根據(jù)文件的拓展名判斷所使用的語法格式,沒有文件名時 sass 命令默認(rèn)編譯 .sass 文件,添加 --scss 選項或者使用 scss 命令編譯 SCSS 文件。
3.5. 編碼格式 (Encodings)
在 Ruby 1.9 及以上環(huán)境中運(yùn)行 Sass 時,Sass 對文件的編碼格式比較敏感,首先會根據(jù) CSS spec 判斷樣式文件的編碼格式,如果失敗則檢測 Ruby string encoding。也就是說,Sass 首先檢查 Unicode byte order mark,然后是 @charset 聲明,最后是 Ruby string encoding,假如都沒有檢測到,默認(rèn)使用 UTF-8 編碼。
與 CSS 相同,使用 @charset 可以聲明特定的編碼格式。在樣式文件的起始位置(前面沒有任何空白與注釋)插入 @charset "encoding-name", Sass 將會按照給出的編碼格式編譯文件。注意所使用的編碼格式必須可轉(zhuǎn)換為 Unicode 字符集。
Sass 以 UTF-8 編碼輸出 CSS 文件,當(dāng)且僅當(dāng)編譯后的文件中包含非 ASCII 字符時,才會在輸出文件中添加 @charset 聲明,而在壓縮模式下 (compressed mode) 使用 UTF-8 byte order mark 代替 @charset 聲明語句。
4. CSS 功能拓展 (CSS Extensions)
4.1. 嵌套規(guī)則 (Nested Rules)
Sass 允許將一套 CSS 樣式嵌套進(jìn)另一套樣式中,內(nèi)層的樣式將它外層的選擇器作為父選擇器,例如:
#main p {
color: #00ff00;
width: 97%;
.redbox {
background-color: #ff0000;
color: #000000;
}
}
編譯為
#main p {
color: #00ff00;
width: 97%; }
#main p .redbox {
background-color: #ff0000;
color: #000000; }
嵌套功能避免了重復(fù)輸入父選擇器,而且令復(fù)雜的 CSS 結(jié)構(gòu)更易于管理:
#main {
width: 97%;
p, div {
font-size: 2em;
a { font-weight: bold; }
}
pre { font-size: 3em; }
}
編譯為
#main {
width: 97%; }
#main p, #main div {
font-size: 2em; }
#main p a, #main div a {
font-weight: bold; }
#main pre {
font-size: 3em; }
4.2. 父選擇器 & (Referencing Parent Selectors: &)
在嵌套 CSS 規(guī)則時,有時也需要直接使用嵌套外層的父選擇器,例如,當(dāng)給某個元素設(shè)定 hover 樣式時,或者當(dāng) body 元素有某個 classname 時,可以用 & 代表嵌套規(guī)則外層的父選擇器。
a {
font-weight: bold;
text-decoration: none;
&:hover { text-decoration: underline; }
body.firefox & { font-weight: normal; }
}
編譯為
a {
font-weight: bold;
text-decoration: none; }
a:hover {
text-decoration: underline; }
body.firefox a {
font-weight: normal; }
編譯后的 CSS 文件中 & 將被替換成嵌套外層的父選擇器,如果含有多層嵌套,最外層的父選擇器會一層一層向下傳遞:
#main {
color: black;
a {
font-weight: bold;
&:hover { color: red; }
}
}
編譯為
#main {
color: black; }
#main a {
font-weight: bold; }
#main a:hover {
color: red; }
& 必須作為選擇器的第一個字符,其后可以跟隨后綴生成復(fù)合的選擇器,例如
#main {
color: black;
&-sidebar { border: 1px solid; }
}
編譯為
#main {
color: black; }
#main-sidebar {
border: 1px solid; }
當(dāng)父選擇器含有不合適的后綴時,Sass 將會報錯。
4.3. 屬性嵌套 (Nested Properties)
有些 CSS 屬性遵循相同的命名空間 (namespace),比如 font-family, font-size, font-weight 都以 font 作為屬性的命名空間。為了便于管理這樣的屬性,同時也為了避免了重復(fù)輸入,Sass 允許將屬性嵌套在命名空間中,例如:
.funky {
font: {
family: fantasy;
size: 30em;
weight: bold;
}
}
編譯為
.funky {
font-family: fantasy;
font-size: 30em;
font-weight: bold; }
命名空間也可以包含自己的屬性值,例如:
.funky {
font: 20px/24px {
family: fantasy;
weight: bold;
}
}
編譯為
.funky {
font: 20px/24px;
font-family: fantasy;
font-weight: bold; }
4.4. 占位符選擇器 %foo (Placeholder Selectors: %foo)
Sass 額外提供了一種特殊類型的選擇器:占位符選擇器 (placeholder selector)。與常用的 id 與 class 選擇器寫法相似,只是 # 或 . 替換成了 %。必須通過 @extend 指令調(diào)用,更多介紹請查閱 @extend-Only Selectors。
// 占位符選擇器 %
%message-shared {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
.message {
@extend %message-shared;
}
.message {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
當(dāng)占位符選擇器單獨使用時(未通過 @extend 調(diào)用),不會編譯到 CSS 文件中。
5. 注釋 /* */ 與 // (Comments: /* */ and //)
Sass 支持標(biāo)準(zhǔn)的 CSS 多行注釋 /* */,以及單行注釋 //,前者會 被完整輸出到編譯后的 CSS 文件中,而后者則不會,例如:
/* 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; }
編譯為
/* 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; }
將 ! 作為多行注釋的第一個字符表示在壓縮輸出模式下保留這條注釋并輸出到 CSS 文件中,通常用于添加版權(quán)信息。
插值語句 (interpolation) 也可寫進(jìn)多行注釋中輸出變量值:
$version: "1.2.3";
/* This CSS is generated by My Snazzy Framework version #{$version}. */
編譯為
/* This CSS is generated by My Snazzy Framework version 1.2.3. */
6. SassScript
在 CSS 屬性的基礎(chǔ)上 Sass 提供了一些名為 SassScript 的新功能。 SassScript 可作用于任何屬性,允許屬性使用變量、算數(shù)運(yùn)算等額外功能。
通過 interpolation,SassScript 甚至可以生成選擇器或?qū)傩悦?,這一點對編寫 mixin 有很大幫助。
6.1. Interactive Shell
Interactive Shell 可以在命令行中測試 SassScript 的功能。在命令行中輸入 sass -i,然后輸入想要測試的 SassScript 查看輸出結(jié)果:
$ sass -i
>> "Hello, Sassy World!"
"Hello, Sassy World!"
>> 1px + 1px + 1px
3px
>> #777 + #777
#eeeeee
>> #777 + #888
white
6.2. 變量 $ (Variables: $)
SassScript 最普遍的用法就是變量,變量以美元符號開頭,賦值方法與 CSS 屬性的寫法一樣:
$width: 5em;
直接使用即調(diào)用變量:
#main {
width: $width;
}
變量支持塊級作用域,嵌套規(guī)則內(nèi)定義的變量只能在嵌套規(guī)則內(nèi)使用(局部變量),不在嵌套規(guī)則內(nèi)定義的變量則可在任何地方使用(全局變量)。將局部變量轉(zhuǎn)換為全局變量可以添加 !global聲明:
#main {
$width: 5em !global;
width: $width;
}
#sidebar {
width: $width;
}
編譯為
#main {
width: 5em;
}
#sidebar {
width: 5em;
}
6.3. 數(shù)據(jù)類型 (Data Types)
SassScript 支持 6 種主要的數(shù)據(jù)類型:
數(shù)字,1, 2, 13, 10px字符串,有引號字符串與無引號字符串,"foo", 'bar', baz顏色,blue, #04a3f9, rgba(255,0,0,0.5)布爾型,true, false空值,null數(shù)組 (list),用空格或逗號作分隔符,1.5em 1em 0 2em, Helvetica, Arial, sans-serifmaps, 相當(dāng)于 JavaScript 的 object,(key1: value1, key2: value2)
SassScript 也支持其他 CSS 屬性值,比如 Unicode 字符集,或 !important 聲明。然而Sass 不會特殊對待這些屬性值,一律視為無引號字符串。
6.3.1. 字符串 (Strings)
SassScript 支持 CSS 的兩種字符串類型:有引號字符串 (quoted strings),如 "Lucida Grande" 'http://sass-lang.com';與無引號字符串 (unquoted strings),如 sans-serif bold,在編譯 CSS 文件時不會改變其類型。只有一種情況例外,使用 #{} (interpolation) 時,有引號字符串將被編譯為無引號字符串,這樣便于在 mixin 中引用選擇器名:
@mixin firefox-message($selector) {
body.firefox #{$selector}:before {
content: "Hi, Firefox users!";
}
}
@include firefox-message(".header");
編譯為
body.firefox .header:before {
content: "Hi, Firefox users!"; }
6.3.2. 數(shù)組 (Lists)
數(shù)組 (lists) 指 Sass 如何處理 CSS 中 margin: 10px 15px 0 0 或者 font-face: Helvetica, Arial, sans-serif 這樣通過空格或者逗號分隔的一系列的值。事實上,獨立的值也被視為數(shù)組 —— 只包含一個值的數(shù)組。
數(shù)組本身沒有太多功能,但 Sass list functions 賦予了數(shù)組更多新功能:nth 函數(shù)可以直接訪問數(shù)組中的某一項;join 函數(shù)可以將多個數(shù)組連接在一起;append 函數(shù)可以在數(shù)組中添加新值;而 @each 指令能夠遍歷數(shù)組中的每一項。
數(shù)組中可以包含子數(shù)組,比如 1px 2px, 5px 6px 是包含 1px 2px 與 5px 6px 兩個數(shù)組的數(shù)組。如果內(nèi)外兩層數(shù)組使用相同的分隔方式,需要用圓括號包裹內(nèi)層,所以也可以寫成 (1px 2px) (5px 6px)。變化是,之前的 1px 2px, 5px 6px 使用逗號分割了兩個子數(shù)組 (comma-separated),而 (1px 2px) (5px 6px) 則使用空格分割(space-separated)。
當(dāng)數(shù)組被編譯為 CSS 時,Sass 不會添加任何圓括號(CSS 中沒有這種寫法),所以 (1px 2px) (5px 6px) 與 1px 2px, 5px 6px 在編譯后的 CSS 文件中是完全一樣的,但是它們在 Sass 文件中卻有不同的意義,前者是包含兩個數(shù)組的數(shù)組,而后者是包含四個值的數(shù)組。
用 () 表示不包含任何值的空數(shù)組(在 Sass 3.3 版之后也視為空的 map)??諗?shù)組不可以直接編譯成 CSS,比如編譯 font-family: () Sass 將會報錯。如果數(shù)組中包含空數(shù)組或空值,編譯時將被清除,比如 1px 2px () 3px 或 1px 2px null 3px。
基于逗號分隔的數(shù)組允許保留結(jié)尾的逗號,這樣做的意義是強(qiáng)調(diào)數(shù)組的結(jié)構(gòu)關(guān)系,尤其是需要聲明只包含單個值的數(shù)組時。例如 (1,) 表示只包含 1 的數(shù)組,而 (1 2 3,) 表示包含 1 2 3 這個以空格分隔的數(shù)組的數(shù)組。
6.3.3. Maps
Maps represent an association between keys and values, where keys are used to look up values. They make it easy to collect values into named groups and access those groups dynamically. They have no direct parallel in CSS, although they’re syntactically similar to media query expressions: scss $map: (key1: value1, key2: value2, key3: value3); Unlike lists, maps must always be surrounded by parentheses and must always be comma-separated. Both the keys and values in maps can be any SassScript object. A map may only have one value associated with a given key (although that value may be a list). A given value may be associated with many keys, though. Like lists, maps are mostly manipulated using SassScript functions. The map-get function looks up values in a map and the map-merge function adds values to a map. The @each directive can be used to add styles for each key/value pair in a map. The order of pairs in a map is always the same as when the map was created. Maps can also be used anywhere lists can. When used by a list function, a map is treated as a list of pairs. For example, (key1: value1, key2: value2) would be treated as the nested list key1 value1, key2 value2 by list functions. Lists cannot be treated as maps, though, with the exception of the empty list. () represents both a map with no key/value pairs and a list with no elements. Note that map keys can be any Sass data type (even another map) and the syntax for declaring a map allows arbitrary SassScript expressions that will be evaluated to determine the key. Maps cannot be converted to plain CSS. Using one as the value of a variable or an argument to a CSS function will cause an error. Use the inspect($value) function to produce an output string useful for debugging maps. 中文簡要說明: Maps可視為鍵值對的集合,鍵被用于定位值 在css種沒有對應(yīng)的概念。 和Lists不同Maps必須被圓括號包圍,鍵值對被都好分割 。 Maps中的keys和values可以是sassscript的任何對象。(包括任意的sassscript表達(dá)式 arbitrary SassScript expressions) 和Lists一樣Maps主要為sassscript函數(shù)服務(wù),如 map-get函數(shù)用于查找鍵值,map-merge函數(shù)用于map和新加的鍵值融合,@each命令可添加樣式到一個map中的每個鍵值對。 Maps可用于任何Lists可用的地方,在List函數(shù)中 Map會被自動轉(zhuǎn)換為List , 如 (key1: value1, key2: value2)會被List函數(shù)轉(zhuǎn)換為 key1 value1, key2 value2 ,反之則不能。(網(wǎng)友Soledad提供)
6.3.4. 顏色 (Colors)
Any CSS color expression returns a SassScript Color value. This includes a large number of named colors which are indistinguishable from unquoted strings. In compressed output mode, Sass will output the smallest CSS representation of a color. For example, #FF0000 will output as red in compressed mode, but blanchedalmond will output as #FFEBCD. A common issue users encounter with named colors is that since Sass prefers the same output format as was typed in other output modes, a color interpolated into a selector becomes invalid syntax when compressed. To avoid this, always quote named colors if they are meant to be used in the construction of a selector.
6.4. 運(yùn)算 (Operations)
所有數(shù)據(jù)類型均支持相等運(yùn)算 == 或 !=,此外,每種數(shù)據(jù)類型也有其各自支持的運(yùn)算方式。
6.4.1. 數(shù)字運(yùn)算 (Number Operations)
SassScript 支持?jǐn)?shù)字的加減乘除、取整等運(yùn)算 (+, -, *, /, %),如果必要會在不同單位間轉(zhuǎn)換值。
p {
width: 1in + 8pt;
}
編譯為
p {
width: 1.111in; }
關(guān)系運(yùn)算 <, >, <=, >= 也可用于數(shù)字運(yùn)算,相等運(yùn)算 ==, != 可用于所有數(shù)據(jù)類型。
6.4.1.1. 除法運(yùn)算 / (Division and /)
/ 在 CSS 中通常起到分隔數(shù)字的用途,SassScript 作為 CSS 語言的拓展當(dāng)然也支持這個功能,同時也賦予了 / 除法運(yùn)算的功能。也就是說,如果 / 在 SassScript 中把兩個數(shù)字分隔,編譯后的 CSS 文件中也是同樣的作用。
以下三種情況 / 將被視為除法運(yùn)算符號:
如果值,或值的一部分,是變量或者函數(shù)的返回值如果值被圓括號包裹如果值是算數(shù)表達(dá)式的一部分
p {
font: 10px/8px; // Plain CSS, no division
$width: 1000px;
width: $width/2; // Uses a variable, does division
width: round(1.5)/2; // Uses a function, does division
height: (500px/2); // Uses parentheses, does division
margin-left: 5px + 8px/2px; // Uses +, does division
}
編譯為
p {
font: 10px/8px;
width: 500px;
width: 1;
height: 250px;
margin-left: 9px;
}
如果需要使用變量,同時又要確保 / 不做除法運(yùn)算而是完整地編譯到 CSS 文件中,只需要用 #{} 插值語句將變量包裹。
p {
$font-size: 12px;
$line-height: 30px;
font: #{$font-size}/#{$line-height};
}
編譯為
p {
font: 12px/30px; }
6.4.2. 顏色值運(yùn)算 (Color Operations)
顏色值的運(yùn)算是分段計算進(jìn)行的,也就是分別計算紅色,綠色,以及藍(lán)色的值:
p {
color: #010203 + #040506;
}
計算 01 + 04 = 05 02 + 05 = 07 03 + 06 = 09,然后編譯為
p {
color: #050709; }
使用 color functions 比計算顏色值更方便一些。
數(shù)字與顏色值之間也可以進(jìn)行算數(shù)運(yùn)算,同樣也是分段計算的,比如
p {
color: #010203 * 2;
}
計算 01 * 2 = 02 02 * 2 = 04 03 * 2 = 06,然后編譯為
p {
color: #020406; }
需要注意的是,如果顏色值包含 alpha channel(rgba 或 hsla 兩種顏色值),必須擁有相等的 alpha 值才能進(jìn)行運(yùn)算,因為算術(shù)運(yùn)算不會作用于 alpha 值。
p {
color: rgba(255, 0, 0, 0.75) + rgba(0, 255, 0, 0.75);
}
編譯為
p {
color: rgba(255, 255, 0, 0.75); }
顏色值的 alpha channel 可以通過 opacify 或 transparentize 兩個函數(shù)進(jìn)行調(diào)整。
$translucent-red: rgba(255, 0, 0, 0.5);
p {
color: opacify($translucent-red, 0.3);
background-color: transparentize($translucent-red, 0.25);
}
編譯為
p {
color: rgba(255, 0, 0, 0.8);
background-color: rgba(255, 0, 0, 0.25); }
IE 濾鏡要求所有的顏色值包含 alpha 層,而且格式必須固定 #AABBCCDD,使用 ie_hex_str 函數(shù)可以很容易地將顏色轉(zhuǎn)化為 IE 濾鏡要求的格式。
$translucent-red: rgba(255, 0, 0, 0.5);
$green: #00ff00;
div {
filter: progid:DXImageTransform.Microsoft.gradient(enabled='false', startColorstr='#{ie-hex-str($green)}', endColorstr='#{ie-hex-str($translucent-red)}');
}
編譯為
div {
filter: progid:DXImageTransform.Microsoft.gradient(enabled='false', startColorstr=#FF00FF00, endColorstr=#80FF0000);
}
6.4.3. 字符串運(yùn)算 (String Operations)
+ 可用于連接字符串
p {
cursor: e + -resize;
}
編譯為
p {
cursor: e-resize; }
注意,如果有引號字符串(位于 + 左側(cè))連接無引號字符串,運(yùn)算結(jié)果是有引號的,相反,無引號字符串(位于 + 左側(cè))連接有引號字符串,運(yùn)算結(jié)果則沒有引號。
p:before {
content: "Foo " + Bar;
font-family: sans- + "serif";
}
編譯為
p:before {
content: "Foo Bar";
font-family: sans-serif; }
運(yùn)算表達(dá)式與其他值連用時,用空格做連接符:
p {
margin: 3px + 4px auto;
}
編譯為
p {
margin: 7px auto; }
在有引號的文本字符串中使用 #{} 插值語句可以添加動態(tài)的值:
p:before {
content: "I ate #{5 + 10} pies!";
}
編譯為
p:before {
content: "I ate 15 pies!"; }
空的值被視作插入了空字符串:
$value: null;
p:before {
content: "I ate #{$value} pies!";
}
編譯為
p:before {
content: "I ate pies!"; }
6.4.4. 布爾運(yùn)算 (Boolean Operations)
SassScript 支持布爾型的 and or 以及 not 運(yùn)算。
6.4.5. 數(shù)組運(yùn)算 (List Operations)
數(shù)組不支持任何運(yùn)算方式,只能使用 list functions 控制。
6.5. 圓括號 (Parentheses)
圓括號可以用來影響運(yùn)算的順序:
p {
width: 1em + (2em * 3);
}
編譯為
p {
width: 7em; }
6.6. 函數(shù) (Functions)
SassScript 定義了多種函數(shù),有些甚至可以通過普通的 CSS 語句調(diào)用:
p {
color: hsl(0, 100%, 50%);
}
編譯為
p {
color: #ff0000; }
6.6.1. 關(guān)鍵詞參數(shù) (Keyword Arguments)
Sass 函數(shù)允許使用關(guān)鍵詞參數(shù) (keyword arguments),上面的例子也可以寫成:
p {
color: hsl($hue: 0, $saturation: 100%, $lightness: 50%);
}
雖然不夠簡明,但是閱讀起來會更方便。關(guān)鍵詞參數(shù)給函數(shù)提供了更靈活的接口,以及容易調(diào)用的參數(shù)。關(guān)鍵詞參數(shù)可以打亂順序使用,如果使用默認(rèn)值也可以省缺,另外,參數(shù)名被視為變量名,下劃線、短橫線可以互換使用。
通過 Sass::Script::Functions 查看完整的 Sass 函數(shù)列表,參數(shù)名,以及如何自定義函數(shù)。
6.7. 插值語句 #{} (Interpolation: #{})
通過 #{} 插值語句可以在選擇器或?qū)傩悦惺褂米兞浚?/p>
$name: foo;
$attr: border;
p.#{$name} {
#{$attr}-color: blue;
}
編譯為
p.foo {
border-color: blue; }
#{} 插值語句也可以在屬性值中插入 SassScript,大多數(shù)情況下,這樣可能還不如使用變量方便,但是使用 #{} 可以避免 Sass 運(yùn)行運(yùn)算表達(dá)式,直接編譯 CSS。
p {
$font-size: 12px;
$line-height: 30px;
font: #{$font-size}/#{$line-height};
}
編譯為
p {
font: 12px/30px; }
6.8. & in SassScript
Just like when it’s used in selectors, & in SassScript refers to the current parent selector. It’s a comma-separated list of space-separated lists. For example:
.foo.bar .baz.bang, .bip.qux {
$selector: &;
}
The value of $selector is now ((“.foo.bar” “.baz.bang”), “.bip.qux”). The compound selectors are quoted here to indicate that they’re strings, but in reality they would be unquoted. Even if the parent selector doesn’t contain a comma or a space, & will always have two levels of nesting, so it can be accessed consistently.
If there is no parent selector, the value of & will be null. This means you can use it in a mixin to detect whether a parent selector exists:
@mixin does-parent-exist {
@if & {
&:hover {
color: red;
}
} @else {
a {
color: red;
}
}
}
6.9. 變量定義 !default (Variable Defaults: !default)
可以在變量的結(jié)尾添加 !default 給一個未通過 !default 聲明賦值的變量賦值,此時,如果變量已經(jīng)被賦值,不會再被重新賦值,但是如果變量還沒有被賦值,則會被賦予新的值。
$content: "First content";
$content: "Second content?" !default;
$new_content: "First time reference" !default;
#main {
content: $content;
new-content: $new_content;
}
編譯為
#main {
content: "First content";
new-content: "First time reference"; }
變量是 null 空值時將視為未被 !default 賦值。
$content: null;
$content: "Non-null content" !default;
#main {
content: $content;
}
編譯為
#main {
content: "Non-null content"; }
7. @-Rules 與指令 (@-Rules and Directives)
Sass 支持所有的 CSS3 @-Rules,以及 Sass 特有的 “指令”(directives)。這一節(jié)會詳細(xì)解釋,更多資料請查看 控制指令 (control directives) 與 混合指令 (mixin directives) 兩個部分。
7.1. @import
Sass 拓展了 @import 的功能,允許其導(dǎo)入 SCSS 或 Sass 文件。被導(dǎo)入的文件將合并編譯到同一個 CSS 文件中,另外,被導(dǎo)入的文件中所包含的變量或者混合指令 (mixin) 都可以在導(dǎo)入的文件中使用。
Sass 在當(dāng)前地址,或 Rack, Rails, Merb 的 Sass 文件地址尋找 Sass 文件,如果需要設(shè)定其他地址,可以用 :load_paths 選項,或者在命令行中輸入 --load-path 命令。
通常,@import 尋找 Sass 文件并將其導(dǎo)入,但在以下情況下,@import 僅作為普通的 CSS 語句,不會導(dǎo)入任何 Sass 文件。
文件拓展名是 .css;文件名以 http:// 開頭;文件名是 url();@import 包含 media queries。
如果不在上述情況內(nèi),文件的拓展名是 .scss 或 .sass,則導(dǎo)入成功。沒有指定拓展名,Sass 將會試著尋找文件名相同,拓展名為 .scss 或 .sass 的文件并將其導(dǎo)入。
@import "foo.scss";
或
@import "foo";
都會導(dǎo)入文件 foo.scss,但是
@import "foo.css";
@import "foo" screen;
@import "http://foo.com/bar";
@import url(foo);
編譯為
@import "foo.css";
@import "foo" screen;
@import "http://foo.com/bar";
@import url(foo);
Sass 允許同時導(dǎo)入多個文件,例如同時導(dǎo)入 rounded-corners 與 text-shadow 兩個文件:
@import "rounded-corners", "text-shadow";
導(dǎo)入文件也可以使用 #{ } 插值語句,但不是通過變量動態(tài)導(dǎo)入 Sass 文件,只能作用于 CSS 的 url() 導(dǎo)入方式:
$family: unquote("Droid+Sans");
@import url("http://fonts.googleapis.com/css?family=\#{$family}");
編譯為
@import url("http://fonts.googleapis.com/css?family=Droid+Sans");
7.1.1. 分音 (Partials)
如果需要導(dǎo)入 SCSS 或者 Sass 文件,但又不希望將其編譯為 CSS,只需要在文件名前添加下劃線,這樣會告訴 Sass 不要編譯這些文件,但導(dǎo)入語句中卻不需要添加下劃線。
例如,將文件命名為 _colors.scss,便不會編譯 _colours.css 文件。
@import "colors";
上面的例子,導(dǎo)入的其實是 _colors.scss 文件
注意,不可以同時存在添加下劃線與未添加下劃線的同名文件,添加下劃線的文件將會被忽略。
7.1.2. 嵌套 @import
大多數(shù)情況下,一般在文件的最外層(不在嵌套規(guī)則內(nèi))使用 @import,其實,也可以將 @import 嵌套進(jìn) CSS 樣式或者 @media 中,與平時的用法效果相同,只是這樣導(dǎo)入的樣式只能出現(xiàn)在嵌套的層中。
假設(shè) example.scss 文件包含以下樣式:
.example {
color: red;
}
然后導(dǎo)入到 #main 樣式內(nèi)
#main {
@import "example";
}
將會被編譯為
#main .example {
color: red;
}
Directives that are only allowed at the base level of a document, like @mixin or @charset, are not allowed in files that are @imported in a nested context. 這一句不理解
不可以在混合指令 (mixin) 或控制指令 (control directives) 中嵌套 @import。
7.2. @media
Sass 中 @media 指令與 CSS 中用法一樣,只是增加了一點額外的功能:允許其在 CSS 規(guī)則中嵌套。如果 @media 嵌套在 CSS 規(guī)則內(nèi),編譯時,@media 將被編譯到文件的最外層,包含嵌套的父選擇器。這個功能讓 @media 用起來更方便,不需要重復(fù)使用選擇器,也不會打亂 CSS 的書寫流程。
.sidebar {
width: 300px;
@media screen and (orientation: landscape) {
width: 500px;
}
}
編譯為
.sidebar {
width: 300px; }
@media screen and (orientation: landscape) {
.sidebar {
width: 500px; } }
@media 的 queries 允許互相嵌套使用,編譯時,Sass 自動添加 and
@media screen {
.sidebar {
@media (orientation: landscape) {
width: 500px;
}
}
}
編譯為
@media screen and (orientation: landscape) {
.sidebar {
width: 500px; } }
@media 甚至可以使用 SassScript(比如變量,函數(shù),以及運(yùn)算符)代替條件的名稱或者值:
$media: screen;
$feature: -webkit-min-device-pixel-ratio;
$value: 1.5;
@media #{$media} and ($feature: $value) {
.sidebar {
width: 500px;
}
}
編譯為
@media screen and (-webkit-min-device-pixel-ratio: 1.5) {
.sidebar {
width: 500px; } }
7.3. @extend
在設(shè)計網(wǎng)頁的時候常常遇到這種情況:一個元素使用的樣式與另一個元素完全相同,但又添加了額外的樣式。通常會在 HTML 中給元素定義兩個 class,一個通用樣式,一個特殊樣式。假設(shè)現(xiàn)在要設(shè)計一個普通錯誤樣式與一個嚴(yán)重錯誤樣式,一般會這樣寫:
Oh no! You've been hacked!
樣式如下
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
border-width: 3px;
}
麻煩的是,這樣做必須時刻記住使用 .seriousError 時需要參考 .error 的樣式,帶來了很多不變:智能比如加重維護(hù)負(fù)擔(dān),導(dǎo)致 bug,或者給 HTML 添加無語意的樣式。使用 @extend 可以避免上述情況,告訴 Sass 將一個選擇器下的所有樣式繼承給另一個選擇器。
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
@extend .error;
border-width: 3px;
}
上面代碼的意思是將 .error 下的所有樣式繼承給 .seriousError,border-width: 3px; 是單獨給 .seriousError 設(shè)定特殊樣式,這樣,使用 .seriousError 的地方可以不再使用 .error。
其他使用到 .error 的樣式也會同樣繼承給 .seriousError,例如,另一個樣式 .error.intrusion 使用了 hacked.png 做背景,
.error.intrusion {
background-image: url("/image/hacked.png");
}
7.3.1. How it Works
@extend 的作用是將重復(fù)使用的樣式 (.error) 延伸 (extend) 給需要包含這個樣式的特殊樣式(.seriousError),剛剛的例子:
.error {
border: 1px #f00;
background-color: #fdd;
}
.error.intrusion {
background-image: url("/image/hacked.png");
}
.seriousError {
@extend .error;
border-width: 3px;
}
編譯為
.error, .seriousError {
border: 1px #f00;
background-color: #fdd; }
.error.intrusion, .seriousError.intrusion {
background-image: url("/image/hacked.png"); }
.seriousError {
border-width: 3px; }
當(dāng)合并選擇器時,@extend 會很聰明地避免無謂的重復(fù),.seriousError.seriousError 將編譯為 .seriousError,不能匹配任何元素的選擇器(比如 #main#footer )也會刪除。
7.3.2. 延伸復(fù)雜的選擇器 (Extending Complex Selectors)
Class 選擇器并不是唯一可以被延伸 (extend) 的,Sass 允許延伸任何定義給單個元素的選擇器,比如 .special.cool,a:hover 或者 a.user[href^="http://"] 等,例如:
.hoverlink {
@extend a:hover;
}
同 class 元素一樣,a:hover 的樣式將繼承給 .hoverlink。
.hoverlink {
@extend a:hover;
}
a:hover {
text-decoration: underline;
}
編譯為
a:hover, .hoverlink {
text-decoration: underline; }
與上面 .error.intrusion 的例子一樣,所有 a:hover 的樣式將繼承給 .hoverlink,包括其他使用到 a:hover 的樣式,例如:
.hoverlink {
@extend a:hover;
}
.comment a.user:hover {
font-weight: bold;
}
編譯為
.comment a.user:hover, .comment .user.hoverlink {
font-weight: bold; }
7.3.3. 多重延伸 (Multiple Extends)
同一個選擇器可以延伸給多個選擇器,它所包含的屬性將繼承給所有被延伸的選擇器:
.error {
border: 1px #f00;
background-color: #fdd;
}
.attention {
font-size: 3em;
background-color: #ff0;
}
.seriousError {
@extend .error;
@extend .attention;
border-width: 3px;
}
編譯為
.error, .seriousError {
border: 1px #f00;
background-color: #fdd; }
.attention, .seriousError {
font-size: 3em;
background-color: #ff0; }
.seriousError {
border-width: 3px; }
每個 .seriousError 將包含 .error 與 .attention 下的所有樣式,這時,后定義的樣式享有優(yōu)先權(quán):.seriousError 的背景顏色是 #ff0 而不是 #fdd,因為 .attention 在 .error 之后定義。
多重延伸可以使用逗號分隔選擇器名,比如 @extend .error, .attention; 與 @extend .error; @extend.attention 有相同的效果。
7.3.4. 繼續(xù)延伸 (Chaining Extends)
當(dāng)一個選擇器延伸給第二個后,可以繼續(xù)將第二個選擇器延伸給第三個,例如:
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
@extend .error;
border-width: 3px;
}
.criticalError {
@extend .seriousError;
position: fixed;
top: 10%;
bottom: 10%;
left: 10%;
right: 10%;
}
現(xiàn)在,每個 .seriousError 選擇器將包含 .error 的樣式,而 .criticalError 不僅包含 .seriousError 的樣式也會同時包含 .error 的所有樣式,上面的代碼編譯為:
.error, .seriousError, .criticalError {
border: 1px #f00;
background-color: #fdd; }
.seriousError, .criticalError {
border-width: 3px; }
.criticalError {
position: fixed;
top: 10%;
bottom: 10%;
left: 10%;
right: 10%; }
7.3.5. 選擇器列 (Selector Sequences)
暫時不可以將選擇器列 (Selector Sequences),比如 .foo .bar 或 .foo + .bar,延伸給其他元素,但是,卻可以將其他元素延伸給選擇器列:
#fake-links .link {
@extend a;
}
a {
color: blue;
&:hover {
text-decoration: underline;
}
}
編譯為
a, #fake-links .link {
color: blue; }
a:hover, #fake-links .link:hover {
text-decoration: underline; }
7.3.5.1. 合并選擇器列 (Merging Selector Sequences)
有時會遇到復(fù)雜的情況,比如選擇器列中的某個元素需要延伸給另一個選擇器列,這種情況下,兩個選擇器列需要合并,比如:
#admin .tabbar a {
font-weight: bold;
}
#demo .overview .fakelink {
@extend a;
}
技術(shù)上講能夠生成所有匹配條件的結(jié)果,但是這樣生成的樣式表太復(fù)雜了,上面這個簡單的例子就可能有 10 種結(jié)果。所以,Sass 只會編譯輸出有用的選擇器。
當(dāng)兩個列 (sequence) 合并時,如果沒有包含相同的選擇器,將生成兩個新選擇器:第一列出現(xiàn)在第二列之前,或者第二列出現(xiàn)在第一列之前:
#admin .tabbar a {
font-weight: bold;
}
#demo .overview .fakelink {
@extend a;
}
編譯為
#admin .tabbar a,
#admin .tabbar #demo .overview .fakelink,
#demo .overview #admin .tabbar .fakelink {
font-weight: bold; }
如果兩個列 (sequence) 包含了相同的選擇器,相同部分將會合并在一起,其他部分交替輸出。在下面的例子里,兩個列都包含 #admin,輸出結(jié)果中它們合并在了一起:
#admin .tabbar a {
font-weight: bold;
}
#admin .overview .fakelink {
@extend a;
}
編譯為
#admin .tabbar a,
#admin .tabbar .overview .fakelink,
#admin .overview .tabbar .fakelink {
font-weight: bold; }
7.3.6. @extend-Only 選擇器 (@extend-Only Selectors)
有時,需要定義一套樣式并不是給某個元素用,而是只通過 @extend 指令使用,尤其是在制作 Sass 樣式庫的時候,希望 Sass 能夠忽略用不到的樣式。
如果使用普通的 CSS 規(guī)則,最后會編譯出很多用不到的樣式,也容易與其他樣式名沖突,所以,Sass 引入了“占位符選擇器” (placeholder selectors),看起來很像普通的 id 或 class 選擇器,只是 # 或 . 被替換成了 %。可以像 class 或者 id 選擇器那樣使用,當(dāng)它們單獨使用時,不會被編譯到 CSS 文件中。
// This ruleset won't be rendered on its own.
#context a%extreme {
color: blue;
font-weight: bold;
font-size: 2em;
}
占位符選擇器需要通過延伸指令使用,用法與 class 或者 id 選擇器一樣,被延伸后,占位符選擇器本身不會被編譯。
.notice {
@extend %extreme;
}
編譯為
#context a.notice {
color: blue;
font-weight: bold;
font-size: 2em; }
7.3.7. !optional 聲明 (The !optional Flag)
如果 @extend 失敗會收到錯誤提示,比如,這樣寫 a.important {@extend .notice},當(dāng)沒有 .notice 選擇器時,將會報錯,只有 h1.notice 包含 .notice 時也會報錯,因為 h1 與 a 沖突,會生成新的選擇器。
如果要求 @extend 不生成新選擇器,可以通過 !optional 聲明達(dá)到這個目的,例如:
a.important {
@extend .notice !optional;
}
7.3.8. 在指令中延伸 (@extend in Directives)
在指令中使用 @extend 時(比如在 @media 中)有一些限制:Sass 不可以將 @media 層外的 CSS 規(guī)則延伸給指令層內(nèi)的 CSS,這樣會生成大量的無用代碼。也就是說,如果在 @media (或者其他 CSS 指令)中使用 @extend,必須延伸給相同指令層中的選擇器。
下面的例子是可行的:
@media print {
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
@extend .error;
border-width: 3px;
}
}
但不可以這樣:
.error {
border: 1px #f00;
background-color: #fdd;
}
@media print {
.seriousError {
// INVALID EXTEND: .error is used outside of the "@media print" directive
@extend .error;
border-width: 3px;
}
}
希望有一天,瀏覽器可以原生支持 @extend 指令,這樣就可以在任何指令中使用延伸功能,不再受限制了。
7.4. @at-root
The @at-root directive causes one or more rules to be emitted at the root of the document, rather than being nested beneath their parent selectors. It can either be used with a single inline selector:
.parent {
...
@at-root .child { ... }
}
Which would produce:
.parent { ... }
.child { ... }
Or it can be used with a block containing multiple selectors:
.parent {
...
@at-root {
.child1 { ... }
.child2 { ... }
}
.step-child { ... }
}
Which would output the following:
.parent { ... }
.child1 { ... }
.child2 { ... }
.parent .step-child { ... }
7.4.1. @at-root (without: …) and @at-root (with: …)
By default, @at-root just excludes selectors. However, it’s also possible to use @at-root to move outside of nested directives such as @media as well. For example:
@media print {
.page {
width: 8in;
@at-root (without: media) {
color: red;
}
}
}
produces:
@media print {
.page {
width: 8in;
}
}
.page {
color: red;
}
You can use @at-root (without: …) to move outside of any directive. You can also do it with multiple directives separated by a space: @at-root (without: media supports) moves outside of both @media and @supports queries.
There are two special values you can pass to @at-root. “rule” refers to normal CSS rules; @at-root (without: rule) is the same as @at-root with no query. @at-root (without: all) means that the styles should be moved outside of all directives and CSS rules.
If you want to specify which directives or rules to include, rather than listing which ones should be excluded, you can use with instead of without. For example, @at-root (with: rule) will move outside of all directives, but will preserve any CSS rules.
7.5. @debug
The @debug directive prints the value of a SassScript expression to the standard error output stream. It’s useful for debugging Sass files that have complicated SassScript going on. For example:
@debug 10em + 12em;
編譯為
Line 1 DEBUG: 22em
7.6. @warn
The @warn directive prints the value of a SassScript expression to the standard error output stream. It’s useful for libraries that need to warn users of deprecations or recovering from minor mixin usage mistakes. There are two major distinctions between @warn and @debug:
You can turn warnings off with the --quiet command-line option or the :quiet Sass option.A stylesheet trace will be printed out along with the message so that the user being warned can see where their styles caused the warning.
Usage Example:
@mixin adjust-location($x, $y) {
@if unitless($x) {
@warn "Assuming #{$x} to be in pixels";
$x: 1px * $x;
}
@if unitless($y) {
@warn "Assuming #{$y} to be in pixels";
$y: 1px * $y;
}
position: relative; left: $x; top: $y;
}
7.7. @warn
The @error directive throws the value of a SassScript expression as a fatal error, including a nice stack trace. It’s useful for validating arguments to mixins and functions. For example:
@mixin adjust-location($x, $y) {
@if unitless($x) {
@error "$x may not be unitless, was #{$x}.";
}
@if unitless($y) {
@error "$y may not be unitless, was #{$y}.";
}
position: relative; left: $x; top: $y;
}
There is currently no way to catch errors.
8. 控制指令 (Control Directives)
SassScript 提供了一些基礎(chǔ)的控制指令,比如在滿足一定條件時引用樣式,或者設(shè)定范圍重復(fù)輸出格式。控制指令是一種高級功能,日常編寫過程中并不常用到,主要與混合指令 (mixin) 配合使用,尤其是用在 Compass 等樣式庫中。
8.1. if()
The built-in if() function allows you to branch on a condition and returns only one of two possible outcomes. It can be used in any script context. The if function only evaluates the argument corresponding to the one that it will return – this allows you to refer to variables that may not be defined or to have calculations that would otherwise cause an error (E.g. divide by zero).
8.2. @if
當(dāng) @if 的表達(dá)式返回值不是 false 或者 null 時,條件成立,輸出 {} 內(nèi)的代碼:
p {
@if 1 + 1 == 2 { border: 1px solid; }
@if 5 < 3 { border: 2px dotted; }
@if null { border: 3px double; }
}
編譯為
p {
border: 1px solid; }
@if 聲明后面可以跟多個 @else if 聲明,或者一個 @else 聲明。如果 @if 聲明失敗,Sass 將逐條執(zhí)行 @else if 聲明,如果全部失敗,最后執(zhí)行 @else 聲明,例如:
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else if $type == monster {
color: green;
} @else {
color: black;
}
}
編譯為
p {
color: green; }
8.3. @for
@for 指令可以在限制的范圍內(nèi)重復(fù)輸出格式,每次按要求(變量的值)對輸出結(jié)果做出變動。這個指令包含兩種格式:@for $var from
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
編譯為
.item-1 {
width: 2em; }
.item-2 {
width: 4em; }
.item-3 {
width: 6em; }
8.4. @each
@each 指令的格式是 $var in , $var 可以是任何變量名,比如 $length 或者 $name,而
是一連串的值,也就是值列表。
@each 將變量 $var 作用于值列表中的每一個項目,然后輸出結(jié)果,例如:
@each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
編譯為
.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'); }
8.4.1 Multiple Assignment
The @each directive can also use multiple variables, as in @each $var1, $var2, … in . If is a list of lists, each element of the sub-lists is assigned to the respective variable. For example:
@each $animal, $color, $cursor in (puma, black, default),
(sea-slug, blue, pointer),
(egret, white, move) {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
border: 2px solid $color;
cursor: $cursor;
}
}
is compiled to:
.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; }
Since maps are treated as lists of pairs, multiple assignment works with them as well. For example:
@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {
#{$header} {
font-size: $size;
}
}
is compiled to:
h1 {
font-size: 2em; }
h2 {
font-size: 1.5em; }
h3 {
font-size: 1.2em; }
8.5. @while
@while 指令重復(fù)輸出格式直到表達(dá)式返回結(jié)果為 false。這樣可以實現(xiàn)比 @for 更復(fù)雜的循環(huán),只是很少會用到。例如:
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
.item-6 {
width: 12em; }
.item-4 {
width: 8em; }
.item-2 {
width: 4em; }
9. 混合指令 (Mixin Directives)
混合指令(Mixin)用于定義可重復(fù)使用的樣式,避免了使用無語意的 class,比如 .float-left?;旌现噶羁梢园械?CSS 規(guī)則,絕大部分 Sass 規(guī)則,甚至通過參數(shù)功能引入變量,輸出多樣化的樣式。
9.1. 定義混合指令 @mixin (Defining a Mixin: @mixin)
混合指令的用法是在 @mixin 后添加名稱與樣式,比如名為 large-text 的混合通過下面的代碼定義:
@mixin large-text {
font: {
family: Arial;
size: 20px;
weight: bold;
}
color: #ff0000;
}
混合也需要包含選擇器和屬性,甚至可以用 & 引用父選擇器:
@mixin clearfix {
display: inline-block;
&:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html & { height: 1px }
}
9.2. 引用混合樣式 @include (Including a Mixin: @include)
使用 @include 指令引用混合樣式,格式是在其后添加混合名稱,以及需要的參數(shù)(可選):
.page-title {
@include large-text;
padding: 4px;
margin-top: 10px;
}
編譯為
.page-title {
font-family: Arial;
font-size: 20px;
font-weight: bold;
color: #ff0000;
padding: 4px;
margin-top: 10px; }
也可以在最外層引用混合樣式,不會直接定義屬性,也不可以使用父選擇器。
@mixin silly-links {
a {
color: blue;
background-color: red;
}
}
@include silly-links;
編譯為
a {
color: blue;
background-color: red; }
混合樣式中也可以包含其他混合樣式,比如
@mixin compound {
@include highlighted-background;
@include header-text;
}
@mixin highlighted-background { background-color: #fc0; }
@mixin header-text { font-size: 20px; }
混合樣式中應(yīng)該只定義后代選擇器,這樣可以安全的導(dǎo)入到文件的任何位置。
9.3. 參數(shù) (Arguments)
參數(shù)用于給混合指令中的樣式設(shè)定變量,并且賦值使用。在定義混合指令的時候,按照變量的格式,通過逗號分隔,將參數(shù)寫進(jìn)圓括號里。引用指令時,按照參數(shù)的順序,再將所賦的值對應(yīng)寫進(jìn)括號:
@mixin sexy-border($color, $width) {
border: {
color: $color;
width: $width;
style: dashed;
}
}
p { @include sexy-border(blue, 1in); }
編譯為
p {
border-color: blue;
border-width: 1in;
border-style: dashed; }
混合指令也可以使用給變量賦值的方法給參數(shù)設(shè)定默認(rèn)值,然后,當(dāng)這個指令被引用的時候,如果沒有給參數(shù)賦值,則自動使用默認(rèn)值:
@mixin sexy-border($color, $width: 1in) {
border: {
color: $color;
width: $width;
style: dashed;
}
}
p { @include sexy-border(blue); }
h1 { @include sexy-border(blue, 2in); }
編譯為
p {
border-color: blue;
border-width: 1in;
border-style: dashed; }
h1 {
border-color: blue;
border-width: 2in;
border-style: dashed; }
9.3.1. 關(guān)鍵詞參數(shù) (Keyword Arguments)
混合指令也可以使用關(guān)鍵詞參數(shù),上面的例子也可以寫成:
p { @include sexy-border($color: blue); }
h1 { @include sexy-border($color: blue, $width: 2in); }
雖然不夠簡明,但是閱讀起來會更方便。關(guān)鍵詞參數(shù)給函數(shù)提供了更靈活的接口,以及容易調(diào)用的參數(shù)。關(guān)鍵詞參數(shù)可以打亂順序使用,如果使用默認(rèn)值也可以省缺,另外,參數(shù)名被視為變量名,下劃線、短橫線可以互換使用。
9.3.2. 參數(shù)變量 (Variable Arguments)
有時,不能確定混合指令需要使用多少個參數(shù),比如一個關(guān)于 box-shadow 的混合指令不能確定有多少個 ‘shadow’ 會被用到。這時,可以使用參數(shù)變量 … 聲明(寫在參數(shù)的最后方)告訴 Sass 將這些參數(shù)視為值列表處理:
@mixin box-shadow($shadows...) {
-moz-box-shadow: $shadows;
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
.shadows {
@include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
編譯為
.shadowed {
-moz-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
-webkit-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
}
參數(shù)變量也可以用在引用混合指令的時候 (@include),與平時用法一樣,將一串值列表中的值逐條作為參數(shù)引用:
@mixin colors($text, $background, $border) {
color: $text;
background-color: $background;
border-color: $border;
}
$values: #ff0000, #00ff00, #0000ff;
.primary {
@include colors($values...);
}
編譯為
.primary {
color: #ff0000;
background-color: #00ff00;
border-color: #0000ff;
}
You can use variable arguments to wrap a mixin and add additional styles without changing the argument signature of the mixin. If you do so, even keyword arguments will get passed through to the wrapped mixin. For example:
@mixin wrapped-stylish-mixin($args...) {
font-weight: bold;
@include stylish-mixin($args...);
}
.stylish {
// The $width argument will get passed on to "stylish-mixin" as a keyword
@include wrapped-stylish-mixin(#00ff00, $width: 100px);
}
上面注釋內(nèi)的意思是:$width 參數(shù)將會傳遞給 stylish-mixin 作為關(guān)鍵詞。
9.4. 向混合樣式中導(dǎo)入內(nèi)容 (Passing Content Blocks to a Mixin)
在引用混合樣式的時候,可以先將一段代碼導(dǎo)入到混合指令中,然后再輸出混合樣式,額外導(dǎo)入的部分將出現(xiàn)在 @content 標(biāo)志的地方:
@mixin apply-to-ie6-only {
* html {
@content;
}
}
@include apply-to-ie6-only {
#logo {
background-image: url(/logo.gif);
}
}
編譯為
* html #logo {
background-image: url(/logo.gif);
}
為便于書寫,@mixin 可以用 = 表示,而 @include 可以用 + 表示,所以上面的例子可以寫成:
=apply-to-ie6-only
* html
@content
+apply-to-ie6-only
#logo
background-image: url(/logo.gif)
注意: 當(dāng) @content 在指令中出現(xiàn)過多次或者出現(xiàn)在循環(huán)中時,額外的代碼將被導(dǎo)入到每一個地方。
9.4.1. Variable Scope and Content Blocks
The block of content passed to a mixin are evaluated in the scope where the block is defined, not in the scope of the mixin. This means that variables local to the mixin cannot be used within the passed style block and variables will resolve to the global value:
$color: white;
@mixin colors($color: blue) {
background-color: $color;
@content;
border-color: $color;
}
.colors {
@include colors { color: $color; }
}
編譯為
.colors {
background-color: blue;
color: white;
border-color: blue;
}
Additionally, this makes it clear that the variables and mixins that are used within the passed block are related to the other styles around where the block is defined. For example:
#sidebar {
$sidebar-width: 300px;
width: $sidebar-width;
@include smartphone {
width: $sidebar-width / 3;
}
}
10. 函數(shù)指令 (Function Directives)
Sass 支持自定義函數(shù),并能在任何屬性值或 Sass script 中使用:
$grid-width: 40px;
$gutter-width: 10px;
@function grid-width($n) {
@return $n * $grid-width + ($n - 1) * $gutter-width;
}
#sidebar { width: grid-width(5); }
編譯為
#sidebar {
width: 240px; }
與 mixin 相同,也可以傳遞若干個全局變量給函數(shù)作為參數(shù)。一個函數(shù)可以含有多條語句,需要調(diào)用 @return 輸出結(jié)果。
自定義的函數(shù)也可以使用關(guān)鍵詞參數(shù),上面的例子還可以這樣寫:
#sidebar { width: grid-width($n: 5); }
建議在自定義函數(shù)前添加前綴避免命名沖突,其他人閱讀代碼時也會知道這不是 Sass 或者 CSS 的自帶功能。
自定義函數(shù)與 mixin 相同,都支持 variable arguments
11. 輸出格式 (Output Style)
Sass 默認(rèn)的 CSS 輸出格式很美觀也能清晰反映文檔結(jié)構(gòu),為滿足其他需求 Sass 也提供了多種輸出格式。
Sass 提供了四種輸出格式,可以通過 :style option 選項設(shè)定,或者在命令行中使用 --style 選項。
11.1. :nested
Nested (嵌套)樣式是 Sass 默認(rèn)的輸出格式,能夠清晰反映 CSS 與 HTML 的結(jié)構(gòu)關(guān)系。選擇器與屬性等單獨占用一行,縮進(jìn)量與 Sass 文件中一致,每行的縮進(jìn)量反映了其在嵌套規(guī)則內(nèi)的層數(shù)。當(dāng)閱讀大型 CSS 文件時,這種樣式可以很容易地分析文件的主要結(jié)構(gòu)。
#main {
color: #fff;
background-color: #000; }
#main p {
width: 10em; }
.huge {
font-size: 10em;
font-weight: bold;
text-decoration: underline; }
11.2. :expanded
Expanded 輸出更像是手寫的樣式,選擇器、屬性等各占用一行,屬性根據(jù)選擇器縮進(jìn),而選擇器不做任何縮進(jìn)。
#main {
color: #fff;
background-color: #000;
}
#main p {
width: 10em;
}
.huge {
font-size: 10em;
font-weight: bold;
text-decoration: underline;
}
11.3. :compact
Compact 輸出方式比起上面兩種占用的空間更少,每條 CSS 規(guī)則只占一行,包含其下的所有屬性。嵌套過的選擇器在輸出時沒有空行,不嵌套的選擇器會輸出空白行作為分隔符。
#main { color: #fff; background-color: #000; }
#main p { width: 10em; }
.huge { font-size: 10em; font-weight: bold; text-decoration: underline; }
11.4. :compressed
Compressed 輸出方式刪除所有無意義的空格、空白行、以及注釋,力求將文件體積壓縮到最小,同時也會做出其他調(diào)整,比如會自動替換占用空間最小的顏色表達(dá)方式。
#main{color:#fff;background-color:#000}#main p{width:10em}.huge{font-size:10em;font-weight:bold;text-decoration:underline}
12. 拓展 Sass (Extending Sass)
Sass 提供了很多高級自定義功能,使用這些功能需要有良好的 Ruby 基礎(chǔ)。
12.1. 自定義 Sass 函數(shù) (Defining Custom Sass Functions)
注意:本文內(nèi)容來自官網(wǎng):地址
通過 Ruby API 可以自定義 Sass 函數(shù),具體請查看 source documentation。
12.2. 存儲緩存 (Cache Stores)
Sass caches parsed documents so that they can be reused without parsing them again unless they have changed. By default, Sass will write these cache files to a location on the filesystem indicated by :cache_location. If you cannot write to the filesystem or need to share cache across ruby processes or machines, then you can define your own cache store and set the:cache_store option. For details on creating your own cache store, please see the source documentation.
12.3. 自定義導(dǎo)入 (Custom Importers)
Sass importers are in charge of taking paths passed to @import and finding the appropriate Sass code for those paths. By default, this code is loaded from the filesystem, but importers could be added to load from a database, over HTTP, or use a different file naming scheme than what Sass expects.
Each importer is in charge of a single load path (or whatever the corresponding notion is for the backend). Importers can be placed in the :load_paths array alongside normal filesystem paths.
When resolving an @import, Sass will go through the load paths looking for an importer that successfully imports the path. Once one is found, the imported file is used.
User-created importers must inherit from Sass::Importers::Base.
柚子快報激活碼778899分享:rust Sass學(xué)習(xí)記錄
推薦鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。