Use trailing ampersand (&) as a class combination selector, not a descendant selector

断了今生、忘了曾经 提交于 2020-01-05 04:15:30

问题


I want to apply a class .highlight to a bunch of different elements and style them according to the element type. I could do this:

input[type="text"].highlight {...}
select.highlight {...}
someOtherSelector.hightlight {...}

But I'm trying to use the trailing ampersand (&) to make my code more succinct.

I've tried the following:

.highlight {

    input[type="text"].& {
        border: 1px solid $brand-purple;
    }
}

But I get the following error:

Error: property "input" must be followed by a ':'

I've also tried:

.highlight {

    input[type="text"]& {
        border: 1px solid $brand-purple;
    }
}

But I get the following error:

Invalid CSS after "[type="text"]": expected "{", was "&" "&" may only be used at the beginning of a compound selector.

Is there a way around this, or can this just not be done in SASS?


回答1:


Use #{&} instead of just .&. And use @at-root which allows you to break out of your nesting structure entirely to the "root" of your nesting tree.

Write this in SASS:

.highlight {

  @at-root input[type="text"]#{&} {
      border: 1px solid $brand-purple;
  }
}

This will complied in CSS to:

input[type="text"].highlight {
  border: 1px solid purple;
}

Hope this helps!




回答2:


You need to reorganize your scss a bit, what you need is:

input[type="text"]  {
  &.highlight {
    border: 1px solid $brand-purple;
  }
}

*Edit after your update, you can use @at-root:

.highlight {
  @at-root {
    input[type="text"]  {
      &.highlight {
        border: 1px solid $brand-purple;
      }
    }
  }
}


来源:https://stackoverflow.com/questions/41188790/use-trailing-ampersand-as-a-class-combination-selector-not-a-descendant-sel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!