Subscribe

SCSS Nesting

✍️

Nesting in SCSS Explained

1 Aug, 2020 · 3 min read

This is, without a doubt, my favorite part of SCSS. Nesting is used to nest code inside each other; it’s very versatile. In the long term, it will make you think twice about naming because it’s easier to sort.

Basic SCSS Nesting

Basic nesting can be used as follows.

Let’s take the following HTML

<ul>
  <li>
    <a href="https://daily-dev-tips.com/" target="_blank">Daily Dev Tips</a>
  </li>
</ul>

We can then make some cool SCSS like this.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  li {
    display: inline-block;
    background: #333;
    a {
      padding: 10px;
      color: #efefef;
    }
  }
}

This will then render in the following CSS.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
ul li {
  display: inline-block;
  background: #333;
}
ul li a {
  padding: 10px;
  color: #efefef;
}

This looks like the following Codepen.

See the Pen SCSS Basic Nesting by Chris Bongers (@rebelchris) on CodePen.

SCSS Dash Nesting

Another cool one is class nesting.

<div class="box">
  <div class="box-inner">
    <h1 class="box-inner-title">Welcome 👏</h1>
  </div>
</div>

And we can then use the following SCSS.

.box {
  background: #ebc3db;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  &-inner {
    background: #c09bd8;
    padding: 20px 40px;
    border-radius: 20px;
    &-title {
      color: #ede3e9;
      font-size: 2rem;
    }
  }
}

Cool right! It makes it more manageable and clear what a part of your CSS is for.

SCSS Sub Nesting

We can also use sub-nesting for our pseudo-selectors.

.box {
  &-inner {
    &:hover {
      background: #9f84bd;
    }
  }
}

As you can see, these also use the & sign and can be used for hovers but also nth-child etc.

This will result in the following Codepen.

See the Pen SCSS Basic Nesting Dash by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Modifying an SVG path with CSS

10 Dec, 2022 · 2 min read

Modifying an SVG path with CSS

Animate an SVG path with CSS

9 Dec, 2022 · 2 min read

Animate an SVG path with CSS

Join 2099 devs and subscribe to my newsletter