翻譯自sass官方文檔: http://sass-lang.com/documentation/file.SASS_REFERENCE.html#css_extensions
嵌套規(guī)則 (Nested Rules)
Sass 允許將一個 CSS 樣式嵌套進(jìn)另一個樣式中,內(nèi)層樣式僅適用于外層樣式的選擇器范圍內(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布局中多層嵌套的選擇器 要簡單得多。 例如:
#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; }
引用父選擇器:& (Referencing Parent Selectors: &) {#parent-selector}
有些時候需要直接使用嵌套外層的父選擇器,這個就很有用了,例如,你可能喜歡給選擇器指定 hover樣式,或者當(dāng)body元素具有某個樣式時,在這些情況下,你可以
&
字符來明確地表示插入指定父選擇器。 例如:
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; }
&
將替換為呈現(xiàn)在CSS文件中的父選擇器。這意味著,如果你有一個多層嵌套的規(guī)則,父選擇器將在被
&
替換之前完全分解。 例如:
#main { color: black; a { font-weight: bold; &:hover { color: red; } } }
編譯為:
#main { color: black; } #main a { font-weight: bold; } #main a:hover { color: red; }
&
必須出現(xiàn)在的選擇器的開頭位置(愚人碼頭注:也就是作為選擇器的第一個字符),但可以跟隨后綴,將被添加到父選擇的后面。 例如:
#main { color: black; &-sidebar { border: 1px solid; } }
編譯為:
#main { color: black; } #main-sidebar { border: 1px solid; }
父選擇器
&
被作為一個后綴的時候,Sass 將拋出一個錯誤。
嵌套屬性 (Nested Properties)
CSS中有一些屬性遵循相同的“命名空間”;比如,
font-family
,
font-size
, 和
font-weight
都在
font
命名空間中。在CSS中,如果你想在同一個命名空間中設(shè)置一串屬性,你必須每次都輸出來。Sass為此提供了一個快捷方式:只需要輸入一次命名空間,然后在其內(nèi)部嵌套子屬性。例如:
.funky { font: { family: fantasy; size: 30em; weight: bold; } }
編譯為:
.funky { font-family: fantasy; font-size: 30em; font-weight: bold; }
命名空間也可以有自己的屬性值。例如:
.funky { font: 20px/24px fantasy { weight: bold; } }
編譯為:
.funky { font: 20px/24px fantasy; font-weight: bold; }
占位符選擇器:
%foo
(Placeholder Selectors:
%foo
)
Sass 支持一種特殊類型的選擇器,叫做”占位符選擇器” (placeholder selector)。這些看起來像 class 和 id 選擇器,除了
#
或
.
用
%
替換。他們需要在
@extend
指令
中使用;有關(guān)詳細(xì)信息,請參閱
@extend
-Only Selectors
。
當(dāng)他們單獨(dú)使用的時候,即沒有使用
@extend
的,使用占位符選擇器的規(guī)則集將不會被渲染為CSS。