4. CSS 功能拓展 (CSS Extensions)
4. CSS 功能拓展 (CSS Extensions)
4.1. 嵌套规则 (Nested Rules)
Sass 允许将一套 CSS 样式嵌套进另一套样式中,内层的样式将它外层的选择器作为父选择器,例如:
1. #main p {2. color: #00ff00;3. width: 97%;5. .redbox {6. background-color: #ff0000;7. color: #000000;8. }9. }
编译为
1. #main p {2. color: #00ff00;3. width: 97%; }4. #main p .redbox {5. background-color: #ff0000;6. color: #000000; }
嵌套功能避免了重复输入父选择器,而且令复杂的 CSS 结构更易于管理:
1. #main {2. width: 97%;4. p, div {5. font-size: 2em;6. a { font-weight: bold; }7. }9. pre { font-size: 3em; }10. }
编译为
1. #main {2. width: 97%; }3. #main p, #main div {4. font-size: 2em; }5. #main p a, #main div a {6. font-weight: bold; }7. #main pre {8. font-size: 3em; }
4.2. 父选择器 & (Referencing Parent Selectors: &)
在嵌套 CSS 规则时,有时也需要直接使用嵌套外层的父选择器,例如,当给某个元素设定 hover 样式时,或者当 body 元素有某个 classname 时,可以用 & 代表嵌套规则外层的父选择器。
1. a {2. font-weight: bold;3. text-decoration: none;4. &:hover { text-decoration: underline; }5. body.firefox & { font-weight: normal; }6. }
编译为
1. a {2. font-weight: bold;3. text-decoration: none; }4. a:hover {5. text-decoration: underline; }6. body.firefox a {7. font-weight: normal; }
编译后的 CSS 文件中 & 将被替换成嵌套外层的父选择器,如果含有多层嵌套,最外层的父选择器会一层一层向下传递:
1. #main {2. color: black;3. a {4. font-weight: bold;5. &:hover { color: red; }6. }7. }
编译为
1. #main {2. color: black; }3. #main a {4. font-weight: bold; }5. #main a:hover {6. color: red; }
& 必须作为选择器的第一个字符,其后可以跟随后缀生成复合的选择器,例如
1. #main {2. color: black;3. &-sidebar { border: 1px solid; }4. }
编译为
1. #main {2. color: black; }3. #main-sidebar {4. border: 1px solid; }
当父选择器含有不合适的后缀时,Sass 将会报错。
4.3. 属性嵌套 (Nested Properties)
有些 CSS 属性遵循相同的命名空间 (namespace),比如 font-family, font-size, font-weight 都以 font 作为属性的命名空间。为了便于管理这样的属性,同时也为了避免了重复输入,Sass 允许将属性嵌套在命名空间中,例如:
1. .funky {2. font: {3. family: fantasy;4. size: 30em;5. weight: bold;6. }7. }
编译为
1. .funky {2. font-family: fantasy;3. font-size: 30em;4. font-weight: bold; }
命名空间也可以包含自己的属性值,例如:
1. .funky {2. font: 20px/24px {3. family: fantasy;4. weight: bold;5. }6. }
编译为
1. .funky {2. font: 20px/24px;3. font-family: fantasy;4. font-weight: bold; }
4.4. 占位符选择器 %foo (Placeholder Selectors: %foo)
Sass 额外提供了一种特殊类型的选择器:占位符选择器 (placeholder selector)。与常用的 id 与 class 选择器写法相似,只是 # 或 . 替换成了 %。必须通过 @extend 指令调用,更多介绍请查阅 @extend-Only Selectors。
当占位符选择器单独使用时(未通过 @extend 调用),不会编译到 CSS 文件中。
