alanbuchanan alanbuchanan - 4 months ago 12
Sass (Sass) Question

Elegantly targeting an element within a selector three nesting levels deep, without breaking linting rules

I am refactoring some SCSS, and I have come across a nesting issue using BEM syntax in my SCSS files.

My linting rules state that I cannot use more than three levels of nesting.

However, sometimes I may want to target an element within a modifier selector in my SCSS file.

This is my approach:

.block {
&__element {
&--modifier {
&::after {
// Four levels deep :(
}
}
}
}


This is the only logical way I see around it:

.block {
&__element {
&--modifier {
// Three levels deep
}

&--modifier::after {
// Three levels deep
}
}
}


I am not a fan of this approach because I don't like repeating the modifier classname.

Is there a better solution for this?

Answer

The purpose of a linting tool is to force developers softly to develop maintainable code. Doing some (probably harder to write and read) workaround is the complete opposite of this goal.

You've provided a completely valid use-case, where 4 levels are the cleanest way to achieve the goal. Therefore you should either

adjust the linting rules (.scss-lint.yaml)

  NestingDepth:
    max_depth: 4

or (if it doesn't occur that often) disable the warning inline:

// scss-lint:disable NestingDepth