“&”选择器选择什么?

ass CSS

LEY小宇宙

2020-03-19

Codepen中有一个CSS选择器&:hover,该选择器与什么匹配?

第2310篇《“&”选择器选择什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
猪猪GO 2020.03.19

究竟。在Sass中,您可能会遇到这样的事情...

 div {
    background: green;

    p {
        background: red;

        &:hover {
            background: blue;
        }

        &:active {
           background: blue; 
        }
    }   
}

...转换为CSS时会变成这样:

div {
    background: green;
}

div p {
    background: red;
}

div p:hover {
    background: blue;
}

div p:active {
    blue;
}

编辑:从&hover:到&:hover

Gil小哥 2020.03.19

我相信&符是Sass的功能。从文档:

引用父选择器:&

有时以默认方式以外的其他方式使用嵌套规则的父选择器很有用。例如,当选择器悬停时或body元素具有特定类时,您可能希望具有特殊的样式。在这些情况下,您可以使用&字符明确指定应将父选择器插入的位置。

乐米亚 2020.03.19

鲜为人知的一种用法是,您可以将&符号添加到样式的末尾,以便父选择器成为子选择器。

例如:

 h3
   font-size: 20px
   margin-bottom: 10px

 .some-parent-selector &
   font-size: 24px
   margin-bottom: 20px

变成

  h3 {
    font-size: 20px;
    margin-bottom: 10px;
  }

  .some-parent-selector h3 {
    font-size: 24px;
    margin-bottom: 20px;
  }

您可以在此处了解更多信息和使用

http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android