Sass 嵌套规则和属性

Sass Nested Rules

Sass allows you to nest CSS selectors in the same way as HTML.

Please see this example of Sass code for the website navigation:

SCSS 语法:

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }
  li {
    display: inline-block;
  }
  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

Note that in Sass,ul,li and a Nested selectors in nav in the selector.

While in CSS, the rules are defined one by one (not nested):

CSS Syntax:

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}

Because you can nest properties in Sass, it is clearer and easier to read than standard CSS.

Sass Nested Properties

Maraming CSS attribute may have the same prefix, such as:

  • font-family
  • font-size
  • font-weight
  • text-align
  • text-transform
  • text-overflow

通过使用 Sass,您可以将它们编写为嵌套属性:

SCSS 语法:

font: {
  family: Helvetica, sans-serif;
  size: 18px;
  weight: bold;
}
text: {
  align: center;
  transform: lowercase;
  overflow: hidden;
}

Sass 转译器会将以上代码转换为普通 CSS:

CSS 输出:

font-family: Helvetica, sans-serif;
font-size: 18px;
font-weight: bold;
text-align: center;
text-transform: lowercase;
text-overflow: hidden;