Lit Element - Constrain Global Styles in a Web Component

03/19/2022, Sat
Categories: #JavaScript

Linking Stylesheet in the Template

To use even a basic css library will cause some styles to be applied globally to the entire page, but you wish to localize the styling to just the web component which you are defining.

Importing the third party css library in the static style definition will not bring in the styles.

static styles = css`

// This won't work
@import 'bulma/css/bulma.css';

...
`

Instead, add the link tag which references another stylesheet within the template. That stylesheet will be the one which will provide the import of the css library.

<link rel="stylesheet" href="./stuff.css">
<div id="my-custom-element">
  Stuff
</div>
/* stuff.css */

// This will work
@import 'bulma/css/bulma.css';

...