Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the '&' selector select?

Tags:

sass

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

like image 871
ilivewithian Avatar asked Jul 04 '12 20:07

ilivewithian


3 Answers

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.

like image 175
Chris Laplante Avatar answered Nov 19 '22 19:11

Chris Laplante


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

like image 47
João Paulo Macedo Avatar answered Nov 19 '22 18:11

João Paulo Macedo


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

like image 5
user1095118 Avatar answered Nov 19 '22 19:11

user1095118