“Close-up of lines of code on a computer screen” by Ilya Pavlov on Unsplash

Writing Maintainable SCSS

Some tips and tricks for writing styles that won’t make you tear out your hair later

Michael Flores
5 min readAug 2, 2018

--

Some of these tips are things I’ve found on the web over years and put into practice, and found that they were as helpful as advertised (happy to include links whenever I come across a source). Others are things I noticed during my own development. All are subject to opinion, and there may be other ways to solve some of the problems put forth here: let me know in the comments!

Avoid deep nesting by never going more than 3 levels deep (Inception)

Deep nesting causes a performance hit because it outputs long selector strings.

It messes with specificity, due to lengthy selectors which forces the creation of subsequent selectors with greater specificity to override styles further up in the cascade.

It also reduces portability and maintainability of styles.

When selectors become this long, you’re likely writing CSS that is:

  • Strongly coupled to the HTML (fragile)
  • Overly specific (powerful)
  • Not reusable
  • If you are writing well-formed HTML and CSS, you should never need to do this.

Avoiding deep nesting in React projects

  • It’s common to modularize CSS in React via stylesheet imports at the component level. This presents an inherent challenge in preventing unintended style bleed and being explicit about what styles are shared across components.
  • To prevent unintended style bleed, the root element of a component should have a unique, camelCased name (i.e. `myCustomModalComponent`). Never duplicate root element class names.
  • In the SCSS, the first line should be this class name so that all styles therein are scoped to this component.
  • Elements below the root element should follow BEM practices. As a general rule, blocks within blocks likely belong in their own React component. Nevertheless, blocks within blocks should begin a new “block”, and not extend the classname from an existing

--

--

Michael Flores

Fan of tech, code, and coffee. Occasional starter of new things. Learn more: https://michaelflores.io