Trusted answers to developer questions

Nesting CSS selectors with Sass

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

You must have noticed that HTML has a very specific structure and visual hierarchy with different components nested within one another. This is not the case with standard CSS.

However, Sass lets you nest your CSS selectors in a way that is very similar to the hierarchal nesting in HTML. Consider the example below that shows styling using SCSS and CSS:

SCSS

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

CSS

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}



Note that the ul, li, and a selectors are nested inside the nav selector in SCSS. This makes your CSS code very readable and more organized. However, it is important to keep in mind that too many nested rules will make your code more difficult to debug and maintain.

RELATED TAGS

nesting
css
selectors
sass
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?