John the Painter
John the Painter

Reputation: 2615

Sass – concat to @at-root selector

I'm using @at-root quite a lot (as classes are dynamically being added and removed from the body) and I wondered if something like the below is possible?

header.main {
    @at-root body[class*="contact"] #{&}, body.text-single #{&} {
        background-color: white;
        &.header-is--hidden {
            background-color: red; // I know this won't work
        }
    }
}

Rather than having to write:

header.main {
    @at-root body[class*="contact"] #{&}, body.text-single #{&} {
        background-color: white;
    }
    @at-root body[class*="contact"].header-is--hidden #{&}, body.text-single.header-is--hidden #{&} {
        background-color: red;
    }
}

Upvotes: 0

Views: 274

Answers (1)

Jakob E
Jakob E

Reputation: 4936

I wondered if something like the below is possible?

Yes it is

You can save the header.main selector in a variable and use interpolation to render it out – like:

header.main {
  $sel: &;  //  contains header.main

  @at-root body[class*="contact"], body.text-single {
    #{$sel} {
      background-color: white;
    }
    &.header-is--hidden #{$sel} {
      background-color: red;
    }
  }
}

CSS output

body[class*="contact"] header.main, 
body.text-single header.main {
  background-color: white;
}
body[class*="contact"].header-is--hidden header.main, 
body.text-single.header-is--hidden header.main {
  background-color: red;
}

Upvotes: 2

Related Questions