Search code examples
cssweb-componentlit-element

Webcomponents css class not usable in slot


Say i have the following css file:

.testClass{
    color:red;
}

And the following index.html file:

<html>
  <head>
    <meta charset="utf-8">
    <title>Portal Demo</title>
    <link rel="stylesheet" href="test.css">
    <script type="module" src="../build/portal-app.js"></script>
    <style>
      p {
        border: solid 1px blue;
        padding: 8px;
      }
    </style>
  </head>
  <body>
  <i class="fa fa-times"></i>
    <portal-app>
      <p>This is child cosntent</p>
    </portal-app>
  </body>
</html>

And inside of the portal-app i have the following code:

   import  'sdk-button'
@customElement('portal-app')
export class PortalApp extends LitElement {
    render() {
        return html`
      ${this.renderWidget()} 
    `;
    }

    renderWidget() {
        import("./views/my-test-element");
        return html`
<i class="fa fa-times"></i>
        <sdk-icon-button text="hello marc"><p slot="icon" class="testClass">hello</p></sdk-icon-button>
    `;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'portal-app': PortalApp;
    }
}

When i run this the color of the .p tag is not red and i can't see the style. however i just add a normal p tag to html the color correctly turns red.

But it seems that inside my slot i am unable to pass the css class that is defined in the index.html can anyone tell me why?


Solution

  • This is expected behaviour as per Web Components Shadow DOM specifications.

    In your code

    <p slot="icon" class="testClass">hello</p>
    

    This template is part of PortalApp Web Component. Which means this markup is in the Shadow DOM of Portal App web component. No css styles from outside (index.html) in you case can get applied to this markup. vice- versa is also true, i.e, no CSS leak from the component to outside of component will happen