Nesting CSS selectors with Sass

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.

Copyright ©2024 Educative, Inc. All rights reserved