Ampersand (parent selector) inside nested selector

2019-01-17 16:13发布

问题:

This question already has an answer here:

  • Modifying the middle of a selector in Sass (adding/removing classes, etc.) 2 answers

Is this not documented or just not possible?

#parent {
  #child {
    width: 75%;

    .additional_parent_class & {
      width: 50%;
    }
  }
}

This will basically turn into:

.additional_parent_class #parent #child {
  width: 50%;
}

While this makes sense because of the implementation of the ampersand and how it's used. What if I'm trying to get it to achieve this:

#parent.additional_parent_class #child {
  width: 50%;
}

The only way I have been able to achieve this is by writing another rule outside of the child declarations:

#parent{
  #child {
    width: 75%;
  }

  &.additional_parent_class #child {
    width: 50%;
  }
}

While this isn't necessarily a 'pain in the butt' in this implementation, it seems counter productive if #child has children of its own that will now need to be duplicated in both rules.

Anyway, maybe I'm just being picky, but it would be great if there were more ways to traverse through the selectors.

回答1:

Although it is not currently possible, this and many similar improvements to the & syntax are slated for release in Sass 3.3. You can follow the discussion about the feature on the Sass issue here.



回答2:

I agree it would be very helpful. Unfortunately, it's not currently possible in SASS (or any other CSS preprocessor I know of).



回答3:

This is capable in v3.4 might be in 3.3 but not sure. I am not a fan of the syntax though. & is much easier. Wish there was something like &^ for an alias :)

#parent {
    #child {
        width: 75%;
        @at-root #{selector-replace(&, '#parent', '#parent.additional_parent_class')} {
            width: 50%;
        }  
    }
}