SCSS 語法:Nesting Rules, 巢狀規則
就那麼簡單: {} 一層,{{}} 兩層,以此類推。在 SCSS 語法裡巢狀規則也很簡單,你就看包幾層的 {} 符號,那就是幾層。
巢狀規則 SCSS 範例
/* 巢狀規則1 */
/* article 與 border-top 一條規則 */
/* article 與 header 一條規則 */
article {
border-top: 1px dashed #eee;
header { margin-bottom: 1.5em; }
}
/* 巢狀規則2 */
/* article 與 header 一條規則 */
/* article 與 section 一條規則 */
article {
header, section { margin-bottom: 1.5em; }
}
/* 巢狀規則3 */
/* article 與 >, ~, +, * 各一條規則(共 4 條規則) */
article {
> h2 { border-top: 1px dashed #eee; }
~ article { padding-top: 1.5em; }
+ footer { margin-top: 0; }
* { color: #000; }
}
/* 巢狀規則4 */
/* Parent Selector - & 參考父選擇器 */
/* a 一條規則 */
/* &:hover 一條規則 */
a {
color: blue;
&:hover { color: red; }
display: inline-block;
line-height: 1.8em;
}
/* 巢狀規則5 */
/* Parent Selector - & 新增內容至選擇器 */
/* article 與 h1 一條規則 */
/* .blog-index & 參考(&)父選擇器形成
".blog-index article",.blog-index article 與 h1 一條規則
*/
article {
h1 { font-size: 2.4em; }
.blog-index & {
h1 { font-size: 2em; }
}
}
/* 巢狀規則6 */
/* Parent Selector - & 與 Modernizr 一起運作 */
/* button 與 backgroud 一條規則 */
/* .no-cssgradients & 參考(&)父選擇器形成
".no-cssgradients button" 一條規則
*/
button {
background: linear-gradient(#444, #222);
.no-cssgradients & { background: #333; }
}
巢狀規則 SCSS 轉成 CSS
@charset "UTF-8";
/* 巢狀規則1 */
article {
border-top: 1px dashed #eee; }
article header {
margin-bottom: 1.5em; }
/* 巢狀規則2 */
article header, article section {
margin-bottom: 1.5em; }
/* 巢狀規則3 */
article > h2 {
border-top: 1px dashed #eee; }
article ~ article {
padding-top: 1.5em; }
article + footer {
margin-top: 0; }
article * {
color: #000; }
/* 巢狀規則4 */
a {
color: blue;
display: inline-block;
line-height: 1.8em; }
a:hover {
color: red; }
/* 巢狀規則5 */
article h1 {
font-size: 2.4em; }
.blog-index article h1 {
font-size: 2em; }
/* 巢狀規則6 */
button {
background: linear-gradient(#444444, #222222); }
.no-cssgradients button {
background: #333; }
父選擇器碰到子選擇器,就形成一條規則。碰到 &(參考) 就形成一條規則。例如以下 SCSS,
a {
color: red;
b {
color: greed;
c {
color:blue;
}
}
}
產生的 CSS,
a {
color: red; }
a b {
color: greed; }
a b c {
color: blue; }
a、ab、abc 一共三條,這樣清楚了嗎。