What’s wrong with Sass nesting? Provide some example.

Technology CommunityCategory: CSSWhat’s wrong with Sass nesting? Provide some example.
VietMX Staff asked 3 years ago

In itself, there’s absolutely nothing wrong with nesting. The feature makes sense. The problem, as is often the case, is not the feature but how we use it.

  • Nesting makes code complicated. For example:
.tabs {
  .tab {
    background: red;

    &:hover {
      background: white;
    }

    .tab-link {
      color: white;

      @at-root #{selector-replace(&, '.tab', '.tab:hover')} { // @at-root jump out at the top level
        color: red;
      }
    }
  }
}
  • The Reference selector & is ambiguous, depending on the way it is used, it can yield a totally different CSS output. For example:
/* SCSS */
.element {
  &:hover {
    color: red;
  }
}

/* CSS */
.element:hover {
  color: red;
}

and:

/* SCSS */
.element {
  & .hover {
    color: red;
  }
}

/* CSS */
.element .hover {
  color: red;
}
  • Unsearchable selectors. Consider:
.block {
  /* Some CSS declarations */

  &--modifier {
    /* Some CSS declarations for the modifier */
  }

  &__element {
    /* Some CSS for the element */

    &--modifier {
      /* Some CSS for the modifier of the element */
    }
  }
}

What if a developer wants to find the CSS from .block__element?