Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Nesting – Sass

Demo

Summary

Sass nesting example:

#my-section {
  h1 {
    color: red;
  }

  p {
    color: blue;
  }
}

Compiled CSS:

#my-section h1 {
  color: red;
}
#my-section p {
  color: blue;
}

To see a live example of this code, view the Demo section below.

Details

In Sass, you can use nesting instead of writing descendant selectors. To start, write out the main selector:

#my-selection {

}

Then add your other selectors and rules inside, like this:

#my-selection {
  h1 {
    color: red;
  }

  p {
    color: blue;
  }
}

To make things easier to read, indent the nested rulesets.

The nesting will result in the following compiled CSS:

#my-section h1 {
  color: red;
}
#my-section p {
  color: blue;
}

Nesting allows you to create multiple descendant selectors in a more compact form, saving you keystrokes.

Exercises

First, recreate the Sass code in the embedded CodePen demo.

Then try changing the selectors, properties, or values.

References

Sass Basics | Sass

@extend | Sass Documentation

Back to: Sass Reference