父级选择器

使用 & 引用父选择器

& 运算符表示 嵌套规则 的父选择器,在将修改类或伪类应用于现有选择器时最常使用:

a {
  color: blue;
  &:hover {
    color: green;
  }
}

结果是:

a {
  color: blue;
}

a:hover {
  color: green;
}

请注意,如果没有 &,上面的示例将导致 a :hover 规则(匹配 <a> 标签内的悬停元素的后代选择器),这不是我们通常想要的嵌套 :hover

"父选择器" 运算符有多种用途。 基本上任何时候你需要以默认方式之外的其他方式组合嵌套规则的选择器。 例如,& 的另一个典型用途是生成重复的类名:

.button {
  &-ok {
    background-image: url("ok.png");
  }
  &-cancel {
    background-image: url("cancel.png");
  }

  &-custom {
    background-image: url("custom.png");
  }
}

output:

.button-ok {
  background-image: url("ok.png");
}
.button-cancel {
  background-image: url("cancel.png");
}
.button-custom {
  background-image: url("custom.png");
}

多个 &

& 可能会在一个选择器中出现多次。 这使得重复引用父选择器而不重复其名称成为可能。

.link {
  & + & {
    color: red;
  }

  & & {
    color: green;
  }

  && {
    color: blue;
  }

  &, &ish {
    color: cyan;
  }
}

将输出:

.link + .link {
  color: red;
}
.link .link {
  color: green;
}
.link.link {
  color: blue;
}
.link, .linkish {
  color: cyan;
}

请注意,& 代表所有父选择器(不仅仅是最近的祖级)所以下面的例子:

.grand {
  .parent {
    & > & {
      color: red;
    }

    & & {
      color: green;
    }

    && {
      color: blue;
    }

    &, &ish {
      color: cyan;
    }
  }
}

结果是:

.grand .parent > .grand .parent {
  color: red;
}
.grand .parent .grand .parent {
  color: green;
}
.grand .parent.grand .parent {
  color: blue;
}
.grand .parent,
.grand .parentish {
  color: cyan;
}

更改选择器顺序

将选择器添加到继承的(父)选择器之前可能很有用。 这可以通过将 & 放在当前选择器之后来完成。 例如,在使用 Modernizr 时,你可能希望根据支持的功能指定不同的规则:

.header {
  .menu {
    border-radius: 5px;
    .no-borderradius & {
      background-image: url('images/button-background.png');
    }
  }
}

选择器 .no-borderradius & 会将 .no-borderradius 添加到其父 .header .menu 的前面,以在输出中形成 .no-borderradius .header .menu

.header .menu {
  border-radius: 5px;
}
.no-borderradius .header .menu {
  background-image: url('images/button-background.png');
}

组合爆炸

& 也可用于在逗号分隔列表中生成选择器的所有可能排列:

p, a, ul, li {
  border-top: 2px dotted #366;
  & + & {
    border-top: 0;
  }
}

这扩展到指定元素的所有可能 (16) 组合:

p,
a,
ul,
li {
  border-top: 2px dotted #366;
}
p + p,
p + a,
p + ul,
p + li,
a + p,
a + a,
a + ul,
a + li,
ul + p,
ul + a,
ul + ul,
ul + li,
li + p,
li + a,
li + ul,
li + li {
  border-top: 0;
}