SASS:& h3、@at-root .Page #{&} section.gallery会导致语法错误

前端开发 2026-07-07
.Article {
   & h3, @at-root .Page #{&} section.gallery { color:red; }
}

预期生成:
.Article h3, .Page .Article section.gallery { color:red; }

当前的行为是抛出一个语法错误 'Invalid CSS after ...'。

如何解决这个错误?

想要达到同样的效果,一些人会这样做:

.Article {
  // 1. Define the styles once
  @mixin shared-styles {
    color:red;
  }

  // 2. Apply to the standard nested selectors
  & h3 { 
    @include shared-styles;
  }

  // 3. Break out of the root for the special case without duplicating styles
  @at-root .Page #{&} section.gallery {
    @include shared-styles;
  }
}

解决方案

只需把它放在选择器的开头,就能正常工作:

.Article {
    @at-root .Page #{&} section.gallery, & h3 { color:red; }
}

它将生成:
.Page .Article section.gallery, .Article h3 { color:red; }

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章