16.5    Nesting with Sass

An enormous relief when writing SCSS documents is the use of a nesting of selectors (selector nesting), as they occur in the HTML document. However, it’s important to keep the nesting within limits to avoid overloading the specificity of CSS, which can lead to a performance brake. I recommend a nesting of two to maximum three levels here. Here’s a simple example of what such a nesting of selectors looks like and what the CSS preprocessor makes of it. Here, the selectors p and h1 are written inside the my-article class.

SCSS File

CSS File

...
.my-article {
  width: 30rem;
  background-color: $color-primary;
  color: $color-primary-font;
  padding: 0.1em;
  margin-bottom: $spacing-std;
  border-radius: 5px;
 
h1 {
  padding-left: 0.5em;
  }
  p {
  background-color: $color-secondary;

...
.my-article {
  width: 30rem;
  background-color: #5f5f5f;
  color: #fff;
  padding: 0.1em;
  margin-bottom: 1em;
  border-radius: 5px;
}

.my-article h1 {
  padding-left: 0.5em;
}

  color: $color-secondary-font;
  padding: 1em;
  }
}

.my-article p {
  background-color: #fff;
  color: #000;
  padding: 1em;
}

SCSS file: /examples/chapter016/16_5/style/style.scss

CSS file: /examples/chapter016/16_5/style/style.css

Table 16.4     The SCSS File and the CSS File after the Preprocessor Run

I think this kind of nesting significantly facilitates my work and also the overview in the SCSS document. The HTML example is the same as in the previous sections and now looks as shown in Figure 16.5.

The HTML File /examples/chapter016/16_5/index.html during Execution

Figure 16.5     The HTML File /examples/chapter016/16_5/index.html during Execution

Nesting is also useful for CSS properties (property nesting), which are grouped under a short name. For example, for the padding group, there are the individual properties padding-top, padding-bottom, padding-left, and padding-right. You know the same from other CSS properties such as background-, margin-, border-, font-, and more. Returning to the padding example, you can implement this CSS property group as a nested property in SCSS as follows.

SCSS File

CSS File

.my-article {
...
  h1 {
 
padding: {
  left: 0.5em;
  top: 0.1em;
  bottom: 0.1em;
  }
 
}
...
}

...
.my-article h1 {
 
padding-left: 0.5em;
  padding-top: 0.1em;
  padding-bottom: 0.1em;
}
...

/examples/chapter016/16_5/style/style2.scss

/examples/chapter016/16_5/style/style2.css

Table 16.5     The SCSS File and the CSS File after the Preprocessor Run