首页 > 技术文章 > scss-&父选择器标识符

ibabyli 2018-10-26 14:58 原文

  在使用选择器嵌套的时候有一种情况需要特别注意,先看一段scss代码实例:

.text a {
  color: blue;
  :hover { color: red }
}

  也许写此段代码目的是为了将其编译成如下css代码:

.text a {
  color: blue;
}
.text a:hover {
  color: red;
}

  但是现实并非如此,它会按照选择器嵌套原则将其编译成如下css代码:

.text a {
  color: blue;
}
.text a :hover {
  color: red;
}

  上面的代码实现的效果是: class为text的所有后代a标签的所有后代元素,当鼠标悬浮时,字体颜色都会变为红色。

  这个时候就可以使用&父选择器标识符,它的作用就相当于一个父选择器的占位符。可以实现class为text的所有后代a标签的元素,当鼠标悬浮时,字体颜色都会变为红色。

.text a {
  color: blue;
  &:hover { color: red }
}

  上面的代码编译的时候,会将&替换为父选择器a,编译后的css代码如下:

.text a {
  color: blue;
}
.text a:hover {
  color: red;
}

  当然,&父选择器标识符并不仅仅用于链接伪类选择器,看如下scss代码实例:

#content aside {
  color: red;
  body.ie & { color: green }
}

  编译为css代码如下:

#content aside {color: red};
body.ie #content aside { color: green }

 

推荐阅读