Sass And SassScript

130 阅读2分钟

Sass相关知识

在css语法基础上增加了变量(variables)、嵌套(nested rules)、混合(mixins)、导入功能(inline imports)

嵌套规则

内层的样式将它外层的选择器作为父选择器 例如:

#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; }

嵌套功能避免了重复输入父选择器,而且令复杂的 CSS 结构更易于管理

父选择器 &

在嵌套 CSS 规则时,有时也需要直接使用嵌套外层的父选择器,例如,当给某个元素设定 hover 样式时,或者当 body 元素有某个 classname 时,可以用 & 代表嵌套规则外层的父选择器。例如:

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:

#main {
  color: black;
  a {
    font-weight: bold;
    &:hover { color: red; }
  }
}

编译为:

#main {
  color: black; }
  #main a {
    font-weight: bold; }
    #main a:hover {
      color: red; }

&作为选择器第一个字符

& 必须作为选择器的第一个字符,其后可以跟随后缀生成复合的选择器,例如:

#main {
  color: black; 
  &-sidebar { border: 1px solid; }
 }

编译为:

#main {
  color: black; }
  #main-sidebar { border: 1px solid; }
 }

当父选择器含有不合适的后缀时,Sass 将会报错。

属性嵌套

有些 CSS 属性遵循相同的命名空间 (namespace),比如 font-family, font-size, font-weight 都以 font 作为属性的命名空间。为了便于管理这样的属性,同时也为了避免了重复输入,Sass 允许将属性嵌套在命名空间中,例如:

.funky {
  font: {
    family: fantasy;
    size: 30em;
    weight: bold;
  }
}

编译为:

.funky {
  font-family: fantasy;
  font-size: 30em;
  font-weight: bold; }

命名空间也可以包含自己的属性值,例如:

.funky {
  font: 20px/24px {
    family: fantasy;
    weight: bold;
  }
}

编译为:

.funky {
  font: 20px/24px;
    font-family: fantasy;
    font-weight: bold; }

占位符选择器

Sass 额外提供了一种特殊类型的选择器:占位符选择器 (placeholder selector)。与常用的 id 与 class 选择器写法相似,只是 # 或 . 替换成了 %。必须通过 @extend 指令调用,当占位符选择器单独使用时(未通过 @extend 调用),不会编译到 CSS 文件中。

注释 /* */ 与 //

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; }

SassScript

变量 $

$width: 5em;

直接使用即调用变量:

#main {
  width: $width;
}

变量支持块级作用域,嵌套规则内定义的变量只能在嵌套规则内使用(局部变量),不在嵌套规则内定义的变量则可在任何地方使用(全局变量)。将局部变量转换为全局变量可以添加 !global 声明:

#main {
  $width: 5em !global;
  width: $width;
}

#sidebar {
  width: $width;
}

编译为:

#main {
  width: 5em;
}

#sidebar {
  width: 5em;
}