How to use `&` and a tag on the same selector

2019-02-17 11:02发布

问题:

I am trying to write a nested selector that selects a certain tag that has a certain attribute, for example

<li foo="bar">

To select this, li[foo="bar"] would work, but I want to nest it under [foo="bar"] using the scss & notation because I have other things with the [foo="bar"] attribute (e.g., <div foo="bar" class="baz">), and I want to group them together. When I try:

[foo = "bar"]{
  &li{
    ...
  }
  &.baz{
    ...
  }
}

It returns an error that says li may only be used at the beginning of a compound selector, and if I try:

[foo = "bar"]{
  li&{
    ...
  }
  &.baz{
    ...
  }
}

then it says & may only be used at the beginning of a compound selector. How can I do this correctly?

回答1:

Last I heard, this is actually an upcoming feature in SASS 3.3 or 3.4.

See this thread for a question similar to yours and this thread for the proposed solution to be included (which, at the time of writing, seems to be &__element).

The issue here isn't the use of [] and & together - it's the use of a plain element in the selector. Your example with .baz should work as expected.



回答2:

The right syntax nowadays would be li#{&}.