五、sass对css的功能拓展

  1. 嵌套规则 (Nested Rules)
    Sass 允许将一套 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; 
}
  1. 父选择器 & (Referencing Parent Selectors: &)
    在嵌套 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.1 复合选择器
& 必须作为选择器的第一个字符,其后可以跟随后缀生成复合的选择器,例如

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

编译为

#main {
  color: black; 
}
#main-sidebar {
    border: 1px solid; 
}
  1. 属性嵌套 (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; 
}
  1. 注释 /* / 与 // (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 文件中,通常用于添加版权信息。

插值语句 (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. */
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容