在編寫css代碼的時候,可能由於嵌套的原因,需要多次重復書寫選擇器。
代碼如下:
#content article h1 { color: #333 } #content article p { margin-bottom: 1.4em } #content aside { background-color: #EEE }
上面的代碼要多次重復#content和article選擇器,非常繁瑣,使用scss即可解決此問題。
代碼如下:
#content { article { h1 { color: #333 } p { margin-bottom: 1.4em } } aside { background-color: #EEE } } /* 編譯后 */ #content article h1 { color: #333 } #content article p { margin-bottom: 1.4em } #content aside { background-color: #EEE }
上面代碼實現了包含選擇器的嵌套,邏輯非常簡單:
那就是使用大括號作為層級區分,一層一層實現嵌套,在編譯的時候再一層一層剝離出來。
群組選擇器的嵌套:
一、父選擇器重復:
來看一段代碼實例:
.container h1, .container h2, .container h3 { margin-bottom: .8em }
上面的群組選擇器中,我們需要不斷的重復書寫.container選擇器。
使用scss就可以避免此問題,代碼如下:
.container { h1, h2, h3 {margin-bottom: .8em} }
二、子選擇器重復
來看一段代碼實例:
nav a, aside a {color: blue}
使用scss就可以避免此問題,代碼如下:
nav, aside { a {color: blue} }
子組合選擇器和同層組合選擇器:
css代碼如下:
article ~ article { border-top: 1px dashed #ccc } article > footer { background: #eee } article dl > dt { color: #333 } article dl > dd { color: #555 }
對應的scss代碼如下:
article { ~ article { border-top: 1px dashed #ccc } > section { background: #eee } dl > { dt { color: #333 } dd { color: #555 } } }
特別說明:~、和+選擇器既可以放在大括號的外部,也可以放在大括號的內部。
