1

I am using webcomponents-lite (Polymer) to create webcomponents.

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <link rel="stylesheet" href="styles.css">
    <script type="text/javascript" src="/static/js/util.js"></script>
</head>
<body class="dark">
    <main>
        <edsp-login-form></edsp-login-form>
    </main>
</body>
</html>

<edsp-login-form> is defined in js file where it uses lit-html. The definition as follows:

@Define('edsp-login-form', {
  style: ``
})

export class Login extends LitComponent {
render() {
    return html`
    <link rel="import" type="css" href="styles.css">`
    <div></div>
  }
}

In this code, how do apply css classes from styles.css to a component <edsp-login-form> ?

Valay
  • 1,991
  • 2
  • 43
  • 98

1 Answers1

0

Option 1: If you're using Shadow DOM, you can't apply external CSS to your component. A solution is to deactivate the Shadow DOM by implementing this in your component:

createRenderRoot() {
  return this;
}

Option 2: If you still want to apply external CSS and use Shadow DOM, you can use CSS variables. In your external CSS you can instance the variable using something like:

name-of-your-component-tag {
  --variable-name-color: #FFF;
}

and then in your component, you can use the CSS variable:

.my-class {
  color: var(--variable-name-color);
}

Option 3: And if you're trying to apply a dark theme, you can use the CSS inside of your component considering the context. In your component you can use CSS like:

:host-context(.dark) .bg {
  background: #000;
}
Luiz Mitidiero
  • 1,130
  • 1
  • 10
  • 22
  • You could apply external CSS to your shadow DOM if you import the CSS into your custom element's js / ts, then within your shadow dom create and append a new style element and add your imported css to the innerHtml of the new style element. – David Mays Aug 23 '23 at 18:05