How do I reference the parent selector at the end?

2019-01-20 18:08发布

问题:

This question already has an answer here:

  • Append the parent selector to the end with Sass 1 answer

How can I turn this:

.btn-primary {
  .open .dropdown-toggle.btn-primary { ... }
}

into

.btn-primary {
  .open .dropdown-toggle& { ... }
}

I keep getting invalid selector after .dropdown-toggle

回答1:

If you read the complete error, it should say this:

"&" may only be used at the beginning of a compound selector.

However, .dropdown-toggle.btn-primary is the same as .btn-primary.dropdown-toggle. So place the parent selector at the beginning:

.btn-primary {
  .open &.dropdown-toggle { color: blue; }
}

As of Sass 3.4, you can do that like this:

.btn-primary {
  .open .dropdown-toggle#{&} { color: blue; }
}


回答2:

No offense, but I'm not sure you understand what is & used for.. Just in case I'm right here is the explanation:

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.

Example:

p{
    background: red;

    &:hover{
        background: blue;
    }

    &:active {
       background: blue; 
    }
} 

Which will be converted to this:

p {
    background:red;
}

p:hover {
    background:red;
}

p:active {
    background:red;
}


标签: sass