What does the '&' selector select?

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


Solution 1:

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.

Solution 2:

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 {
    background: blue;
}

Edit: from &hover: to &:hover

Solution 3:

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