'Increase specificity weight with double selector via Sass

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.



Solution 1:[1]

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;
    }
  } 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1