scss prepend selector to current selector
Asked Answered
D

2

6

Is there a way to prepend a selector directly to the current selector in scss. Consider the following:

.object-fit {
  object-fit: cover;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

is there a way to prepend img so that the output is img.object-fit?

The only way I have seen for prepending is to add & after like so:

.object-fit {
  img & {
  }
}

but this would turn it into a parent child selector: img .object-fit

The normal way would be just to append the second selector with &img but as this has no dot before the selector, that ends up with a different class name: .object-fitimg

So basically the question is is there anyway inside the object fit class to prepend a bare element selector?

Debase answered 7/10, 2019 at 13:37 Comment(6)
Did you try img&?Tynes
@Tynes That's a syntax error in the SCSS parser. Invalid CSS after "img": expected "{", was "&" "&" may only be used at the beginning of a compound selector.Regulate
something like @at-root img#{&}?Cordwood
@Cordwood Put that as an answer, it works. Good job!Regulate
@Cordwood awesome thanks, add an answer and I'll accept when it lets meDebase
Ok, you're welcome! ;)Cordwood
C
5

If you use @at-root and & with interpolation syntax:

 .object-fit {
      @at-root img#{&} {
        color: blue;
      }
    }

Your output will be:

img.object-fit{
  color: blue;
}
Cordwood answered 7/10, 2019 at 13:49 Comment(4)
Why the @at-root? This would be assuming that the goal always is to get out of the current nested selector.Endres
@Trollsyn if I don't use the @at-root it compiles to .object-fit img.object-fitDebase
@Trollsyn no problem! :-)Cordwood
There seem to be limits to this approach, at-root target can only apply to the first selector listed, see github.com/sass/sass/issues/2059Fastidious
F
1

Complete answer here is @at-root selector-append(), which will also work for multiple parent selectors.

Source: https://github.com/sass/sass/issues/2059#issuecomment-218862922

.object-fit,
.non-fit {
  @at-root #{selector-append("img", &)} {
    color: blue;
  }
}

Output

img.object-fit, img.non-fit {
  color: blue;
}
Fastidious answered 16/12, 2022 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.