Sass references parent selectors using an ampersand character inside nested selectors

It's just that when I thought Sass was the coolest thing with sliced ​​bread, he had to go and let me down. I am trying to use ampersand to select the parent of a nested element. This is a difficult selection and its return to unexpected results ...

My sas:

.page--about-us { a { text-decoration:none; } .fa-stack { .fa { color:pink; } a & { &:hover { .fa-circle-thin { color:red; } .fa-twitter { color:blue; } } } } } 

CSS inferred:

 .page--about-us a { text-decoration: none; } .page--about-us .fa-stack .fa { color: pink; } a .page--about-us .fa-stack:hover .fa-circle-thin { color: red; } a .page--about-us .fa-stack:hover .fa-twitter { color: blue; } 

Expected Result (note the placement of the a tag):

 .page--about-us a { text-decoration: none; } .page--about-us .fa-stack .fa { color: pink; } .page--about-us a .fa-stack:hover .fa-circle-thin { color: red; } .page--about-us a .fa-stack:hover .fa-twitter { color: blue; } 

Demo: http://sassmeister.com/gist/8ed68bbe811bc9526f15

+5
source share
2 answers

You can save the parent selector in a variable!

Take the following BEM-like SASS:

 .content-block { &__heading { font-size: 2em; } &__body { font-size: 1em; } &--featured { &__heading { font-size: 4em; font-weight: bold; } } } 

The selector inside .content-block--featured will be .content-block--featured .content-block--featured__heading , which may not be what you are after.

It's not as elegant as a single ampersand, but you can insert a parent selector into a variable! . So, to get what you could do from the above example without hard coding the parent selector:

 .content-block { $p: &; // store parent selector for nested use &__heading { font-size: 2em; } &__body { font-size: 1em; } &--featured { #{$p}__heading { font-size: 4em; font-weight: bold; } } } 

So, OP, in your case, you can try something like this:

 .page--about-us { $about: &; // store about us selector a { text-decoration:none; } .fa-stack { .fa { color:pink; } #{$about} a & { &:hover { .fa-circle-thin { color:red; } .fa-twitter { color:blue; } } } } } 
+6
source

This is normal behavior, as described in the Sass documentation ( link ):

& will be replaced by the parent selector as it appears in CSS . This means that if you have a deeply nested rule, the parent selector will be fully resolved before and will be replaced.

Value:

 .foo { .bar { .baz & { color: red; } } } 

Mark as:

 .baz .foo .bar { color: red; } 

And not :

 .baz .bar { color: red; } 

The correct way to get the expected result:

 .page--about-us { a { text-decoration:none; .fa-stack:hover { .fa-circle-thin { color:red; } .fa-twitter { color:blue; } } } .fa-stack { .fa { color:pink; } } } 
+3
source

Source: https://habr.com/ru/post/1205322/


All Articles