BudiBadu Logo
Samplebadu

SCSS by Example: Nesting

Sass 3.x+

Mirroring HTML hierarchy in stylesheets with this code example showing nested selector syntax, parent selector reference using ampersand, pseudo-class nesting, and how nested rules compile to descendant selectors in CSS.

Code

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

  li {
    display: inline-block;
  }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
    
    // Parent selector reference (&)
    &:hover {
      background-color: #eee;
    }
    
    &.active {
      font-weight: bold;
    }
  }
}

Explanation

Nesting in SCSS allows selectors to be written inside one another, creating a visual hierarchy that mirrors the HTML structure. When compiled, nested selectors are transformed into descendant selectors in the final CSS. For example, ul nested inside nav compiles to nav ul. This feature improves code organization and readability by grouping related styles together and reducing selector repetition.

The ampersand & symbol is a special character that references the parent selector in nested contexts. It enables several important patterns:

  • Pseudo-classes like &:hover, &:focus, &:active compile to selector:hover
  • Pseudo-elements like &::before, &::after for generated content
  • Modifier classes like &.active compile to selector.active
  • BEM notation like &__element and &--modifier for component architecture
  • Suffix patterns like &-suffix for creating related class names

While nesting provides organizational benefits, excessive nesting depth can generate overly specific selectors that are difficult to override and can increase CSS file size. The compiled output specificity increases with each nesting level, potentially creating maintenance challenges. The ampersand can also be placed after selectors for reverse nesting patterns, useful for contextual styling where a parent class affects child appearance.

Code Breakdown

2
ul { ... } nested in nav compiles to nav ul { ... }.
18
&:hover references parent selector, compiles to nav a:hover.
22
&.active combines parent with class, compiles to nav a.active.
12-24
Three levels of nesting create nav a descendant selector with modifiers.