margot_eddie
margot_eddie

Reputation: 207

Pass a stylesheet to a Lit-Element Web component

Is it possible to pass a stylesheet to a web component using lit-element?

I mean in a similiar way to the one used to set up the properties of the web component.

For example, I have this web component and I want to pass it, from the outside, a stylesheet that has to be pushed to the array returned inside "static get styles" after "SharedStyles".

class MyComponent extends LitElement {

  static get properties() {
    return {
      name: { type: String }
    };
  }

  static get styles () {
    return [      
      super.styles,
      SharedStyles,
      css`
       
      `
    ];
  }
}

If I want to set the property "name" i do:

<my-component .name="${"Fred"}"></my-component>

Is there a way to pass a stylesheet to my-component?

Upvotes: 0

Views: 1453

Answers (1)

shabarinath
shabarinath

Reputation: 593

Yes you can. But you need to export css file first.

step 1: create styles.js

import { css } from 'lit-element';
export const styleSheet = css`
  :host{
    // global css
  }
  .cssProp1{
    // your properties
  }
  .cssProp2{
    // your properties
  }
`

Step 2: import css in to your component

import { styleSheet } from styles.js;

static get styles(){
  return styleSheet;
}

Step 3: render html:

render(){
  return html`
    <div class="cssProp1"></div>
    <div class="cssProp2"></div>
  `
}

This will do the job

Upvotes: 1

Related Questions