css – Sass使用嵌套选择器中的&符号引用父选择器

就在我认为Sass是切片面包以来最酷的东西时,它必须让我失望.我正在尝试使用&符来选择嵌套项的父级.这是一个复杂的选择,它返回了一些意想不到的结果……

我的sass:

.page--about-us {
  a {
    text-decoration:none;
  }
  .fa-stack {
    .fa {
      color:pink;
    }
    a & {
      &:hover {
        .fa-circle-thin {
          color:red;
        }
        .fa-twitter {
          color:blue;
        }
      }
    }
  }
}

输出的CSS:

.page--about-us a {
  text-decoration: none;
}
.page--about-us .fa-stack .fa {
  color: pink;
}
a .page--about-us .fa-stack:hover .fa-circle-thin {
  color: red;
}
a .page--about-us .fa-stack:hover .fa-twitter {
  color: blue;
}

预期输出(注意a标签的位置):

.page--about-us a {
  text-decoration: none;
}
.page--about-us .fa-stack .fa {
  color: pink;
}
.page--about-us a .fa-stack:hover .fa-circle-thin {
  color: red;
}
.page--about-us a .fa-stack:hover .fa-twitter {
  color: blue;
}

演示:
http://sassmeister.com/gist/8ed68bbe811bc9526f15

最佳答案
您可以将父选择器存储在变量中!

采取以下类似BEM的SASS:

.content-block {
    &__heading {
        font-size: 2em;
    }

    &__body {
        font-size: 1em;
    }

    &--featured {
        &__heading {
            font-size: 4em;
            font-weight: bold;
        }
    }
}

.content-block中的选择器 – features将是.content-block – featured .content-block – featured__heading,这可能不是你想要的.

它不像单个&符号那么优雅,但你可以将父选择器存储到变量中!因此,在不对父选择器进行硬编码的情况下,从上面的示例中得到您可能想要的内容

.content-block {
    $p: &; // store parent selector for nested use

    &__heading {
        font-size: 2em;
    }

    &__body {
        font-size: 1em;
    }

    &--featured {
        #{$p}__heading {
            font-size: 4em;
            font-weight: bold;
        }
    }
}

所以,OP,在你的情况下,你可能会尝试这样的事情:

.page--about-us {
    $about: &; // store about us selector

    a {
        text-decoration:none;
    }

    .fa-stack {
        .fa {
            color:pink;
        }

        #{$about} a & {
            &:hover {
                .fa-circle-thin {
                    color:red;
                }
                .fa-twitter {
                    color:blue;
                }
            }
        }
    }
}

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效