Last Updated: May 11, 2021
· jkneb

Parent css selector with Sass / Less preprocessor

You surely know it's impossible to "go up" de DOM tree with a CSS selector. It has to be a descending approach, from a parent element to its children. Nothing new here. But guess what, you can achieve the opposite with Sass or Less!

Let's take a concrete situation, you have a element wich can receive multiple classes, each ono of them handles particular parts of the styling.

.elem {
    /* classes to be placed on .elem */
    &.class1 { }
    &.class2 { }

    /* styles for some children */
    p    { }
    .etc { }

    /* apply styles if elem has .elem-wraper as parent */
    .elem-wraper & { }

Here you can see 3 kind of selectors.

The two first lines with the & immediately followed by something will compile exactly like this : .elem.class1 { }

The second block of selectors are meant to target .elem descendants. So the p will be compiled like this : .elem p { )

And finally, you can reference .elem's parent by putting the & at the end of your selector, and it will compile like this : .elem-wraper .elem { }

As @wjonthomas mentioned in the comments, be aware this technique does not allow you to change parent's styles but instead provide you with a new context for .elem, so you can apply new styles to .elem if it has .elem-wraper as parent.

This is just magic :P

7 Responses
Add your response

Great tip. Not a lot of people know about this feature. I use it quite a bit too.

If you don't mind me saying, it might be helpful to others who don't know about this feature if you adjust the title and intro a little. The way it's worded makes it sound like this tip will allow you to select the parent so that you can apply styles to that parent. That's still not possible. What it actually does is allow you apply specific styles to an element only if it is a child of the specified ancestor, which is what your example demonstrates very nicely.

A less confusing title might be something like "Reference a nested rule's parent selector in order to apply different styles to the rule using Sass or Less."

Again, great tip. People will find this very handy!

over 1 year ago ·

Damn right! Only updated the content though as I failed finding a more appropriate/comprehensive title :P

over 1 year ago ·

Yeah, that's a complicated one to put into a short title. Kudos.

over 1 year ago ·

I use it to handle special cases. Very handy.

over 1 year ago ·

Good stuff.

over 1 year ago ·

What if I want to access the parent of .elem ? Is there a way to do that with less ?

over 1 year ago ·

Nope there's no way to access a parent element. But this shouldn't be a problem, just get it normally.

over 1 year ago ·