嵌套规则 引用父级选择器:&

  • Sass 允许将一个 CSS 样式嵌套进另一个样式中,内层样式仅适用于外层样式的选择器范围内(可以理解为层级选择器)
  • 有助于避免父选择器重复,相对于复杂的CSS布局中多层嵌套的选择器 要简单得多
#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; }
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; }
  • & 必须出现在的选择器的开头位置(也就是作为选择器的第一个字符),但可以跟随后缀,将被添加到父选择的后面
#main { color: black; &-sidebar { border: 1px solid; } } 编译为:
#main { color: black; } #main-sidebar { border: 1px solid; }
  • 父选择器 & 被作为一个后缀的时候,Sass 将抛出一个错误

嵌套属性

  • CSS中有一些属性遵循相同的“命名空间”;比如,font-family, font-size, 和 font-weight都在font命名空间中
.funkay { font: { family: fantasy; size: 30em; weight: bold; } } 编译为:
.funkay { font-family: fantasy; font-size: 30em; font-weight: bold; }
  • 命名空间也可以有自己的属性值
.funkay { font: 20px/24px fantasy { weight: bold; } } 编译为:
.funkay { font: 20px/24px fantasy; font-weight: bold; }

注释: / / 和 //

  • 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中,即使在压缩输出模式下。这可用于在你生成的CSS中添加版权声明

  • 使用插值语句 (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. */