【问题标题】:What does the '&' selector select?'&' 选择器选择什么?
【发布时间】:2012-07-05 07:29:57
【问题描述】:

this codepen 中有一个 css 选择器 &:hover 该选择器匹配什么?

【问题讨论】:

  • 如果你仔细看,你可能已经看到 CSS 标签标题旁边写着 (SCSS)。
  • @Truth:假设评论是针对我的,那么是的:我确实看到了。但是,我正在解决问题本身中的明确声明:“......有一个 css 选择器&:hover。”不过,也许我应该更清楚地说明这一点。

标签: sass


【解决方案1】:

我相信与号是Sass 功能。来自文档:

Referencing Parent Selectors: &

有时在其他规则中使用嵌套规则的父选择器很有用 方式比默认方式。例如,你可能想要特别的 选择器悬停时的样式或正文时的样式 元素具有一定的类别。在这些情况下,您可以显式 使用 & 指定父选择器应该插入的位置 字符。

【讨论】:

    【解决方案2】:

    没错。在 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 {
        background: blue;
    }
    

    编辑:从 &hover: 到 &:hover

    【讨论】:

    • 在你的第二个代码块上,不应该是 div p:hover { background: blue; }div p:active { background: blue; } 吗?我只是提到它来清除它......
    • 是的。当然。我道歉。愚蠢的错误。固定。
    【解决方案3】:

    一种不太广为人知的用法是,您可以在样式的末尾添加与号,这样父选择器就变成了子选择器。

    例如:

     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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2014-04-02
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多