On Splitting CSS Selectors

The other day I read a great article by Philip Zastrow on common issues people are having when implementing the BEM methodology for their CSS.

I agree passionatly in most parts, the ones I find most noteworthy being:

  • Use utility classes instead of single-property modifiers.
  • Make generous use of HTML elments when it helps battling scope issues.
  • Avoid large components, better compose complex structures of smaller chunks.

But then Philip suggests using the Sass Parent Selector:

If you are using Sass to write your CSS, then a terrific method exists to make name changing for your compiled CSS very easy. That method is a staple Sass feature called the Referencing Parent Selector, signified by the &.

The ideas sounds tempting: by nesting your source styles as follows you avoid having to repeat the block’s name for its elements and modifiers and let Sass take care of that. This makes changing the name of an entire BEM component very easy:

.block {
  // styles for .block
  &__element {
    // styles for .block__element
    &--modifier {
      // styles for .block__element--modifier
    }
  }
  &--modifier {
    // styles for .block--modifier
  }
}

So when this helps to refactor quickly and reduce repetion, why do I feel the urge to stand up and shout “Objection, Objection!”?

It makes searching virtually impossible. I can’t recount how often I was given an existing project and had to spend way too much time tracking down the sources for selectors. Searching for .block__element--modifier won’t yield any for the above code snippet.

And yes, in a perfect world it should be enough to search for the block’s name or, better yet, simply being able to open a partial with the same name. If we’d only be living in a perfect world though.

In my book the search problem far outweighs the benefits of being able to change a component’s name centrally.

I do a lot of refactoring myself and never felt inefficient when needing to rename lots of classes at once. I rather consider this a issue of the right tooling. In VS Code, for example, selecting a string and repeatedly hitting the shortcut cmd + d selects all following occurances of said string and allows to directly change all at once:

So for the sake of every developer working on a project after you, and quite possibly your future self: Please don’t split your CSS selectors.

#

Leave a Reply