父选择器

父选择器 & 是 Sass 发明的一种特殊选择器,在嵌套选择器中,用于引用外部选择器。它可以以更复杂的方式重用外部选择器,例如添加伪类或在父级之前添加选择器。

当在内部选择器中,使用父选择器时,它会被相应的外部选择器替换。发生这种情况而不是正常的嵌套行为。

scss 语法 css 语法
.alert {
  // The parent selector can be used to add pseudo-classes to the outer selector.
  &:hover {
    font-weight: bold;
  }

  // It can also be used to style the outer selector in a certain context, such as a body set to use a right-to-left language.
  [dir=rtl] & {
    margin-left: 0;
    margin-right: 10px;
  }

  // You can even use it as an argument to pseudo-class selectors.
  :not(&) {
    opacity: 0.8;
  }
}
.alert:hover {
  font-weight: bold;
}
[dir=rtl] .alert {
  margin-left: 0;
  margin-right: 10px;
}
:not(.alert) {
  opacity: 0.8;
}


⚠️注意!
因为父选择器可以被类型选择器替换,例如: h1 ,所以它只允许在复合选择器的开头,其中也允许类型选择器。例如, span& 不允许。
不过,我们正在考虑放宽这一限制。如果您愿意帮助实现这一目标,


添加后缀

您还可以使用父选择器,向外部选择器添加额外的后缀。这在使用像 BEM 这样使用高度结构化类名的方法时特别有用。只要外部选择器以字母数字名称结尾(如类、ID和元素选择器),您就可以使用父选择器添加后缀。

scss 语法 css 语法
.accordion {
  max-width: 600px;
  margin: 4rem auto;
  width: 90%;
  font-family: "Raleway", sans-serif;
  background: #f4f4f4;

  &__copy {
    display: none;
    padding: 1rem 1.5rem 2rem 1.5rem;
    color: gray;
    line-height: 1.6;
    font-size: 14px;
    font-weight: 500;

    &--open {
      display: block;
    }
  }
}
.accordion {
  max-width: 600px;
  margin: 4rem auto;
  width: 90%;
  font-family: "Raleway", sans-serif;
  background: #f4f4f4;
}
.accordion__copy {
  display: none;
  padding: 1rem 1.5rem 2rem 1.5rem;
  color: gray;
  line-height: 1.6;
  font-size: 14px;
  font-weight: 500;
}
.accordion__copy--open {
  display: block;
}

在 SassScript 中

父选择器也可以在 SassScript 中使用。它是一个特殊的表达式,它与使用选择器函数一样,返回当前父选择器的相同的格式:逗号分隔的列表(选择器列表),或者包含空格分隔的列表(复杂选择器),或者包含不带引号的字符串(复合选择器)。

scss 语法 css 语法
.main aside:hover , .sidebar p {
  parent-selector: &;
  // => ((unquote(".main") unquote("aside:hover")),
  //     (unquote(".sidebar") unquote("p")))
}
.main aside:hover, .sidebar p {
  parent-selector: .main aside:hover , .sidebar p;
}

高级嵌套

您可以将 & 用作普通的 SassScript 表达式,这意味着您可以将其传递给函数或将其包含在插值中——甚至在其他选择器中!将它与选择器函数和@at-root 规则结合使用,可以让您以非常强大的方式嵌套选择器。

例如,假设您要编写一个匹配外部选择器和元素选择器的选择器。您可以编写一个像这样的 mixin,它使用该 selector.unify() 函数,使用 & 与用户的选择器相结合。

scss 语法 css 语法
@use "sass:selector";

@mixin unify-parent($child) {
  @at-root #{selector.unify(&, $child)} {
    @content;
  }
}

.wrapper .field {
  @include unify-parent("input") {
    /* ... */
  }
  @include unify-parent("select") {
    /* ... */
  }
}
.wrapper input.field {
  /* ... */
}

.wrapper select.field {
  /* ... */
}