7

In Stencil when you have set shadow: true, styling the host element is as follows

:host {
    color: red;
}

This works. But now I have the following component

@Component({
    tag: 'my-component',
    styleUrl: 'my-component.scss',
    shadow: true
})
export class MyComponent {
    @Element() host: HTMLElement;

    render() {
        this.host.classList.add('is-test');
        return <div>Test</div>;
    }
}

in which I add the is-test class to the host element. Now, to apply styling based on that class I added the following

:host {
    color: red;

    &.is-test {
        background-color: green;
    }
}

I see is-test class on my-component element, but the background-color: green style is not applied. I must be doing something wrong here, any help would be appreciated!

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

1 Answers1

17

You can use :host():

:host {
    color: red;
}

:host(.is-test) {
    background-color: green;
}

By the way: If you want to set the class (or any attribute) on the host element, you can use the <Host> functional component:

import { Host } from '@stencil/core';

// ...

render() {
    return <Host class="is-test"><div>Test</div></Host>;
}
Thomas
  • 8,426
  • 1
  • 25
  • 49
  • Nice! Isn't SCSS supposed to be able to use `:host { &.className{...} }`? I see it compileing to `:host.className {...` but styles not applying. Your solutions works though. – Ben Racicot Sep 07 '21 at 14:16
  • 1
    Yeah, unfortunately that doesn't compile correctly and most likely won't be added because "[nesting is] only intended for simple use cases", see https://github.com/sass/sass/issues/3099 – Thomas Sep 07 '21 at 14:50