Search code examples
csssassweb-componentstenciljs

Ho do I add common css for stenciljs web-components


I am creating bunch of web-components, not sure how do I create common css for stenciljs web-components. Based on documentation I can add globalStyle: 'src/global/app.css', But it seems i can only share css variables. e.g.

:root {
   --font_color: #484848;
   --bg_color--light: #f9f9f9;
}

if I want to have common base css for buttons e.g.

button {
  border-radius: 5px;
  padding: 2px 10px;
}

Which i want to share across all the components | Not sure how to achieve that. Thanks in advance for suggestions.


Solution

  • The globalStyle stylesheet gets distributed along with your app and can indeed be used to write global CSS. E. g. for the www output target, it gets generated as /build/<namespace>.css, and you can then include it into your app with a link:

    <link rel="stylesheet" href="/build/my-app.css" />
    

    However you can't use it to provide base css for elements that are inside a custom element with Shadow DOM enabled (i. e. if you have shadow: true in the component decorator).


    So, as a solution you can use sass partials and modules to achieve what you're trying to do.

    // src/styles/partials/_button.scss
    
    button {
      border-radius: 5px;
      padding: 2px 10px;
    }
    
    // src/components/my-button/my-button.tsx
    
    @Component({
      tag: my-button,
      shadow: true,
      styleUrl: 'my-button.scss',
    })
    export class MyButton {
      render() {
        return <button>Click me</button>
      }
    }
    
    // src/components/my-button/my-button.scss
    
    @use '../../styles/partials/button';