Joel M. Turner

Illustration

Blog

Getting Sassy With Sass: Nesting

As I’m learning to use Sass I decided to jot down some of the basics for reference. Most of this is coming from Hampton Catlin’s Sass Basics course on Treehouse (referral).

Nesting Selectors

The selectors can be nested for ease of writing and reading. This can help organize code in a way that like selectors are together. It also keeps us from having to repeat strings of selectors. A quick example would be:

Sass:

1.selector1 {
2 .selector2 {
3 color: red;
4 }
5}

CSS Output:

1.selector1 .selector2 {
2 color: red;
3}

You can even go deeper if you would like. Let’s take a look at 4 levels deep (the suggested maximum depth for Sass).

Sass:

1.selector1 {
2 .selector2 {
3 color: red;
4 .box {
5 background: blue;
6 h1 {
7 color: green;
8 }
9 }
10 }
11}

CSS Output:

1.selector1 .selector2 {
2 color: red;
3}
4.selector1 .selector2 .box {
5 background: blue;
6}
7.selector1 .selector2 .box h1 {
8 color: green;
9}

Using the & Symbol

There is a helper character that makes referencing parent selectors much easier. This character is the ampersand (&) symbol.

Sass:

1.blog {
2 > h1 {
3 color: red;
4 border: 1px solid red;
5 }
6 .entry {
7 h1 {
8 font-size: 20px;
9 color: blue;
10 }
11 p {
12 font-size: 12px;
13 margin: 20px;
14 html.csscolumns & {
15 column-count: 2;
16 column-gap: 10px;
17 margin: 10px;
18 }
19 }
20 a {
21 color: red;
22 &:hover {
23 color: blue;
24 }
25 }
26 }
27}

CSS Output:

1.blog > h1 {
2 color: red;
3 border: 1px solid red;
4}
5.blog .entry h1 {
6 font-size: 20px;
7 color: blue;
8}
9.blog .entry p {
10 font-size: 12px;
11 margin: 20px;
12}
13html.csscolumns .blog .entry p {
14 column-count: 2;
15 column-gap: 10px;
16 margin: 10px;
17}
18.blog .entry a {
19 color: red;
20}
21.blog .entry a:hover {
22 color: blue;
23}
Discuss this article on Twitter