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.
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
grandparent {
/* grandparent styles */
parent {
/* parent styles */
child {
/* child styles */
}
}
&.specialGrandpa {
child {
/* child styles with special Grandpa */
}
}
&.specialGrandma {
child {
/* child styles with special Grandma*/
}
}
}
CSS Output
grandparent {
/* grandparent styles */
}
grandparent parent {
/* parent styles */
}
grandparent parent child {
/* child styles */
}
grandparent.specialGrandpa child {
/* child styles with special Grandpa */
}
grandparent.specialGrandma child {
/* child styles with special Grandma*/
}
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
.grandparent {
/* grandparent styles */
.parent {
/* parent styles */
.child {
/* child styles */
.specialGrandparent& {
/* child styles with special grandparent*/
}
}
}
}
CSS Output
.grandparent {
/* grandparent styles */
}
.grandparent .parent {
/* parent styles */
}
.grandparent .parent .child {
/* child styles */
}
.specialGrandparent.grandparent .parent .child {
/* child styles with special grandparent*/
}
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.
span:empty:after {
content: '';
position: absolute;
top: -1px;
right: -10px;
left: -1px;
bottom: -10px;
display: block;
background-color: red;
z-index: -1;
}
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