Nesting Style Definitions in Scss

Feature thumb scss

One of the most popular features of Scss is the ability to nest style definitions, and that's what we're going to walk through in this guide.

In traditional CSS it's possible to say that you want to define a set of styles for one or more classes, such as with code like this:

However, it gets trickier when you want to implement styles for DOM elements that are nested within other elements.

For example, if you want to have two container classes on a page:

For the entire page For spots on the page that have code snippets

You might think that you'd need to rename the container classes to have two separate classes. However, that would mean that each time you alter the styles in one container you'll have to remember to go change each of the other similar classes. There are a few ways to share the style definitions in pure CSS (remember that Scss is simply a translator into CSS), however it can be a bit complex.

Thankfully Scss offers an intuitive way to nest styles.

In the example below, we have two container classes. Notice how we have one 'master' container class definition that has a font family and font size. And then if you traverse down to inside of the page-content class I've nested another call to the container class. However, this nested container class is more specific, so the styles that are defined in it will only apply to the DOM elements that are stored inside of the container class nested inside of the page-content div.

See the Pen Scss Course by Jordan Hudgens (@jordanhudgens) on CodePen.