12

As mentioned here on Stack Overflow in another question and MDN tells about the specificity of selectors, I want to slightly increase the weight of my selector via Sass to override some existing styles. Here's an example of the (compiled) CSS.

.parent .parent__child.parent__child { color: red; }

It is more specific than just using .parent .parent__child as a selector.


I have a way to do this via Sass, but I think there should be a better way to do this:

.parent {
    &__child.parent__child { color: red; }
}

Ideally, this would be the best possible setup (the ampersands have to be directly attached to each other since it's not a child selector):

.parent {
    &__child&__child { color: red; }
}

This throws an error and adds a dot between the 'child' selectors. The Sass documentation doesn't say anything about this particular case. Any ideas on how to achieve this?

edit

I know about the interpolation brackets method, but what if the selector is more profound than three or four layers deep? I only want its parent selector to be duplicated, not the whole selector tree.

Asef Hossini
  • 655
  • 8
  • 11
Roy
  • 7,811
  • 4
  • 24
  • 47

1 Answers1

20

There's a special trick in SASS for doubling specificity using interpolation brackets (more on that here and here) since two &'s next to each other is invalid SASS syntax.

.parent {
  &__child {
    &#{&} {
      color: red; 
    }
  } 
}

// compiles to
// .parent__child.parent__child { color: red; }

// You can also do this with deeper nested elements by
// prefacing the interpolation with the ancestor selectors:
.parent {
  &__child {
    .some .ancestor .elements &#{&} {
      color: red;
    }
  }
}

// compiles to
// .some .ancestor .elements .parent__child.parent__child { color: red; }

For those of you who stumble upon this and use LESS, double &&'s are allowed:

.parent {
  &__child {
    && {
      color: red;
    }
  } 
}
chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • @Roy perhaps you should break the selectors out into their own block and preface the interpolation with the parent selectors. something like `.some .ancestor .classes {&} { ... }` -- edited answer to reflect this. – chazsolo Dec 12 '17 at 21:23
  • But then again, I am writing more selectors than I want to. – Roy Dec 13 '17 at 18:56
  • 1
    @Roy there's only so much you can do to fight specificity. If you original selectors are nested 3 or 4 level deep, or more, then perhaps the original structure needs to be readdressed, or perhaps you might consider namespacing with an id. There's obvious pitfalls with this, nor would I recommend using `!important` as some do. – chazsolo Dec 13 '17 at 19:00
  • both `{&}` and `&&` are breaking the build on my typescript project – Paul Pacurar Mar 16 '23 at 18:33