DEV Community

Cover image for How Does Nesting Work in SASS
Richard Rembert
Richard Rembert

Posted on • Edited on

1

How Does Nesting Work in SASS

When you observe the structure of an HTML file, you’ll notice it has a very clear hierarchy:

<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
  </head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

As you can see, HTML has a structure that makes it quite easy to read.

CSS, on the other hand, lacks this visual structure. Which is why it has a tendency to become disorganized quite quickly.

Enter Sass nesting!

Definition

Using nesting, we can nest child selectors inside of the parent selector.

This results in much cleaner and less repetitive code.

Example

Take the following HTML:

<nav class="navbar">
  <ul>
    <li>Home</li>
    <li>Services</li>
    <li>Contact Us</li>
  </ul>
</nav>
Enter fullscreen mode Exit fullscreen mode

Using regular CSS, we would write this like so:

.navbar {
  background-color: red;
  padding: 1rem;
}
.navbar ul {
  list-style: none;
}
.navbar li {
  text-align: center;
  margin: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

There’s a lot of repetition here. Each time we want to style a child of navbar, we have to repeat the class name.

With Sass nesting, we can write much cleaner code.

Like so:

.navbar {
  background-color: red;
  padding: 1rem;
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
  }
}
Enter fullscreen mode Exit fullscreen mode

Using indentation, you can now see the ul and li selectors are neatly nested inside the navbar selector.

We have a much less repetitive syntax, which is far easier to read!

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay