What does the '&' selector select?

前端 未结 3 1771
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 20:56

In this codepen there is a css selector &:hover what does that selector match?

相关标签:
3条回答
  • 2021-02-06 21:46

    I believe the ampersand is a Sass feature. From the docs:

    Referencing Parent Selectors: &

    Sometimes it’s useful to use a nested rule’s parent selector in other ways than the default. For instance, you might want to have special styles for when that selector is hovered over or for when the body element has a certain class. In these cases, you can explicitly specify where the parent selector should be inserted using the & character.

    0 讨论(0)
  • 2021-02-06 21:54

    One usage that is less widely known is you can add the ampersand to the end of a style so the parent selector becomes the child.

    eg:

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

    becomes,

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

    you can read more about & use here

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

    0 讨论(0)
  • 2021-02-06 21:56

    Exactly. In Sass you could have something like this...

     div {
        background: green;
    
        p {
            background: red;
    
            &:hover {
                background: blue;
            }
    
            &:active {
               background: blue; 
            }
        }   
    }
    

    ...which when converted to CSS would become this:

    div {
        background: green;
    }
    
    div p {
        background: red;
    }
    
    div p:hover {
        background: blue;
    }
    
    div p:active {
        blue;
    }
    

    Edit: from &hover: to &:hover

    0 讨论(0)
提交回复
热议问题