Sass Nested Rules and Properties

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 Syntax:

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

Please note that in Sass,ul,li and a The selector is nested in nav in the selector.

In CSS, the rules are defined sequentially (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

Many CSS properties have the same prefix, for example:

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

By using Sass, you can write them as nested properties:

SCSS Syntax:

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

The Sass transpiler will convert the above code to standard CSS:

CSS Output:

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