Categories
CSS Web development

SASS Nested Rules

Nesting is combining of different logic structures. Using SASS, we can combine multiple CSS rules within one another. If you are using multiple selectors, then you can use one selector inside another to create compound selectors.

SASS

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

Look at an example of some Sass code for a site’s navigation:

SCSS Syntax:

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }
  li {
    display: inline-block;
  }
  a {
    display: block;
    padding: 8px 14px;
    text-decoration: none;
  }
}
Notice that in Sass, the ul, li and a selectors are nested inside the nav selector. While in CSS, the rules are defined one by one (not nested):
nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 8px 14px;
  text-decoration: none;
}

You can nest properties in Sass, it is cleaner and easier to read than standard CSS.

Sass Nested Properties

Many CSS properties have the same prefix, like font-family, font-size and font-weight or text-align, text-transform and text-overflow.

With Sass you can write them as nested properties:

SCSS Syntax:

font: {
  family: Helvetica, sans-serif;
  size: 20px;
  weight: bold;
}

text: {
  align: center;
  transform: uppercase;
  overflow: hidden;
}

The Sass transpiler will convert the above to normal CSS:

font-family: Helvetica, sans-serif;
font-size: 20px;
font-weight: bold;

text-align: center;
text-transform: uppercase;
text-overflow: hidden;

Enjoy coding!