Is there a way in Sass to use the ampersand to select the immediate parent, rather than the parent selector of the entire group? For example:
.wrapper{ background-color: $colour_nav_bg; h1{ color: $colour_inactive; .active &{ color: red; } } }
compiles to:
.wrapper h1{ color: grey; } .active .wrapper h1{ color: red }
but what I actually want is:
.wrapper .active h1{ color: red; }
Is the only option to write the SCSS like so?
.wrapper{ background-color: $colour_nav_bg; h1{ color: $colour_inactive; } .active h1{ color: red; } }
The HTML looks like this:
<ul class="wrapper"> <li class="active"> <h1>blah</h1> </li> </ul>
sass Nesting The parent selector (&)Create a new selector that requires both the parent selector and another on the same element by placing the new selector directly after a parent selector. Have the parent appear after a nested selector in the compiled CSS by placing the parent selector after the nested selector.
Sass lets you reference the parent selector of a nested rule using the ampersand (&) symbol –– it's one of Sass' most useful features!
Ampersand or “&” is a powerful feature of SASS. It enhances the readability of code by using nesting statements, which takes an edge over conventional CSS. We can nest the css class any number of times but most of the times it's not required.
The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.
You can work around this today with a mixin like this one:
@mixin if-direct-parent($parent-selector) { $current-sequences: &; $new-sequences: (); @each $sequence in $current-sequences { $current-selector: nth($sequence, -1); $prepended-selector: join($parent-selector, $current-selector); $new-sequence: set-nth($sequence, -1, $prepended-selector); $new-sequences: append($new-sequences, $new-sequence, comma); } @at-root #{$new-sequences} { @content; } }
Since the &
is essentially a list of lists, you can use list functions (nth, set-nth, join and append) to create the selector sequence you want. Then use @at-root
to output the new selector at root-level. Here's how you'd use it:
.grandparent-1, .grandparent-2 { color: red; .child { color: blue; @include if-direct-parent('.parent') { color: green; } } }
Which will output:
.grandparent-1, .grandparent-2 { color: red; } .grandparent-1 .child, .grandparent-2 .child { color: blue; } .grandparent-1 .parent .child, .grandparent-2 .parent .child { color: green; }
As of this writing, there is no Sass selector for the direct parent instead of the root parent of an element. There is &
which (as you know) selects the root parent. There are also %
placeholder selectors which hides a rule until it's been extended.
Sass is open-sourced, so you could contribute a new "direct parent" selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With