Is it possible to get a parent's parent?
I tried & & { }
but that didn't work.
I'm trying to style a child element based on it's grandparent.
Is it possible to get a parent's parent?
I tried & & { }
but that didn't work.
I'm trying to style a child element based on it's grandparent.
Depends on Code Structure, and may Require Some Repetition of Code
You cannot do it directly in most cases (see second example for exception).
If Grandparent is an element
This requires some repetition, but does allow for the grandparent to not be the outermost wrapper (so there could be a great grandparent).
LESS
CSS Output
If Grandparent is a class, ID, etc., and is the outermost wrapper
No repetition involved here, but you cannot have a
great grandparent
in the mix. Also this is only for LESS 1.3.1+ version (earlier version incorrectly add a space):LESS
CSS Output
This code works by appending to the "front" of the grandparent selector, so that is why the grandparent must be a class, ID, or other selector itself.
Addendum
Based on comment about desire to have a red background when the
span
is empty. This does not put the background on the parent, but "fakes" it using the child.You can use a mixin, then you can pass variables to it based on grandparent selector specifics.
Example:
According to LESS's parent selectors feature, it's possible to change selector order by putting the
&
after the items in your nest, thereby accessing the item's parent's parent.LESS code:
CSS result:
You cannot traverse arbitrarily up the DOM with less selectors. Use javascript instead.
The
&
in less stands for declared selector one level up. A shortcut for already defined rule. As opposed to what you allegedly seek.