3

I have a Less mixin like so: http://codepen.io/sirlancelot/pen/QjzzEb?editors=110

// The mixin to toggle containers
#toggle-container(
    @collapsed-selector: ~"&.__collapsible .section--body",
    @expanded-selector: ~"&.__open .section--body"
) {
    @{collapsed-selector}:extend(#section--collapsed) {}
    @{expanded-selector}:extend(#section--expanded) {}
}

I'm wondering if it's possible to change the notation such that the & in the parameter can be expanded to the parent selector just it would be if I were to write it outside of a variable.

If you click "View Compiled" in the CSS section of the Codepen you will see that the & is being outputted directly like so:

#section--collapsed,
.section &.__collapsible .section--body {
    transition: transform ease 250ms;
    transform: scaleY(0);
    transform-origin: top;
    position: absolute;
    width: 100%;
    z-index: 1;
}
#section--expanded,
.section &.__open .section--body {
    transform: scaleY(1);
    position: static;
}

I want the (space)& to be removed (the space and the ampersand).

matpie
  • 17,033
  • 9
  • 61
  • 82
  • 2
    No, it's currently impossible (neither special symbol like ampersand or comma has any special meaning in a selector interpolated variable). Though in this particular case I doubt you need that - since you can write `&@{collapsed-selector}:extend(#section--collapsed) {}` instead (this of course makes it a bit confusing to pass some *descendant* selector in, but counting the use-case itself, it most likely never happens anyway). – seven-phases-max Nov 14 '15 at 02:23
  • @Hynes posted a reasonable alternative below. – matpie Nov 16 '15 at 17:55

1 Answers1

4

You can achieve the result you want, but you can't include the & within the parametric mixin argument. Instead you will need to move it slightly:

#toggle-container(
    @collapsed-selector: ~".__collapsible .section--body",
    @expanded-selector: ~".__open .section--body"
) {
    &@{collapsed-selector}:extend(#section--collapsed) {}
    &@{expanded-selector}:extend(#section--expanded) {}
}

What did I do?

  1. I moved the & out of the parametric mixin arguments area. Why? Because when you escape a string, variable, or value, it is "used as is with no changes except interpolation." This means your ampersand is being left "as is" and not being allowed to reference the parent as you want. Therefore...
  2. I moved the ampersand out your mixin arguments into your ID's CSS so LESS can make the reference to the child's parent (and can compile in the desired way).
Hynes
  • 3,394
  • 3
  • 22
  • 22
  • This works out well enough for me and if I don't need to attach to the parent selector I can just start that parameter with a space. Thanks! – matpie Nov 16 '15 at 17:56