- 嵌套規(guī)則 (Nested Rules)
Sass 允許將一套 CSS 樣式嵌套進另一套樣式中,內(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;
}
- 父選擇器 & (Referencing Parent Selectors: &)
在嵌套 CSS 規(guī)則時,有時也需要直接使用嵌套外層的父選擇器,例如,當給某個元素設(shè)定 hover 樣式時,或者當 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;
}
2.1 復合選擇器
& 必須作為選擇器的第一個字符,其后可以跟隨后綴生成復合的選擇器,例如
#main {
color: black;
&-sidebar { border: 1px solid; }
}
編譯為
#main {
color: black;
}
#main-sidebar {
border: 1px solid;
}
- 屬性嵌套 (Nested Properties)
有些 CSS 屬性遵循相同的命名空間 (namespace),比如 font-family, font-size, font-weight 都以 font 作為屬性的命名空間。為了便于管理這樣的屬性,同時也為了避免了重復輸入,Sass 允許將屬性嵌套在命名空間中,例如:
.funky {
font: {
family: fantasy;
size: 30em;
weight: bold;
}
}
.funky2 {
font: 20px/24px {
family: fantasy;
weight: bold;
}
}
編譯為
.funky {
font-family: fantasy;
font-size: 30em;
font-weight: bold;
}
.funky2 {
font: 20px/24px;
font-family: fantasy;
font-weight: bold;
}
- 注釋 /* / 與 // (Comments: / / and //)
Sass 支持標準的 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) 也可寫進多行注釋中輸出變量值:
$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. */