Control Sass selector concatenation with a Stylelint rule

It’s not necessarily bad to concatenate Sass selectors, but if you need to keep developers from doing it for the purposes of coding standards, this might be helpful!


There’s been some discussion recently about whether Sass selector concatenation is a good idea or a bad idea (if you are unfamiliar with the practice, refer to those links for an explanation). It turns out that, as with any issue in programming style (especially CSS, I feel) it depends on you and your team and your projects whether or not it is a useful or detrimental practice.

For my team at PMC and the projects we work on, however, I have deemed it a detrimental practice. Our code-bases are not “componentized”, and the selector nesting has proven to become unruly and unreadable over time, especially when it comes to reviewing pull requests and cross referencing markup against stylesheets. I’ve also run into the inability to “Find in Folder” because the selectors are not a single string, and that is infuriating.

In sum: as the resident creator of a centralized build step and CSS standards at PMC, I am putting the kibosh on Sass selector concatenation. In addition to communicating it with my team and in our standards documentation, there’s a way to accomplish this with a regular expression in Stylelint via the selector-nested-pattern rule:

{
	'selector-nested-pattern': '^(?!&__|&--|&-|&_).*'
}

Here is a link to the expression on RegEx101. It’s a nice idea to include that link in a comment or in documentation in case something is amiss and troubleshooting is needed. I’m not a RegExpert (whomp) and I feel there is a more concise way to write this one, but it is pretty readable so maybe it’s fine.

It’s important to note that this is a drastic measure, and would make the aforementioned “centralized build step” unusable for code-bases that are already built on this practice. The solution there will be to allow consuming projects to override the central linting rules, but for new projects, it’s seems promising. PMC often outsources site builds to agencies, and this seems like an excellent way to ensure they write CSS according to our standards.

Stylelint also supports regular expression patterns for custom properties, class naming, and keyframes – this will be a far-future-but-maybe-not-that-far-future thing to look into as we fine tune our naming conventions.