matpie
matpie

Reputation: 17522

How do I replace "&" in a Less variable with the parent selector?

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).

Upvotes: 3

Views: 1341

Answers (1)

Hynes
Hynes

Reputation: 3424

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).

Upvotes: 4

Related Questions