Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase specificity weight with double selector via Sass

Tags:

css

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.

like image 566
Roy Avatar asked Dec 12 '17 20:12

Roy


People also ask

How do I increase my selector specificity?

As a special case for increasing specificity, you can duplicate weights from the CLASS or ID columns. Duplicating id, class, pseudo-class or attribute selectors within a compound selector will increase specificity when overriding very specific selectors over which you have no control.

Which selector has the strongest selector specificity?

ID selectors have the highest specificity amongst the CSS selectors: 1, 0, 0, 0. Because of the unique nature of the ID attribute definition, we are usually styling a really specific element when we call up the ID in our CSS. – The specificity is 1, 0, 0, 1 because we have a type selector and an ID selector.

Which selector does not increase specificity?

The :not() pseudo class does not add to the selector specificity, unlike other pseudo-classes. So the specificity of .


1 Answers

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;
    }
  } 
}
like image 131
chazsolo Avatar answered Oct 22 '22 03:10

chazsolo