3

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.

Ankur Soni
  • 746
  • 6
  • 17

2 Answers2

5

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';
Simon Hänisch
  • 4,740
  • 2
  • 30
  • 42
0

The Stencil docs are a bit unclear on this issue. It took me a while to realize the globalStyle config doesn't actually do anything to apply global styles to components with shadow DOM.

If you wish to use the globalStyle globally across all components, you can try the following:

  • Link the globalStyle inside your index.html
  • Also link the globalStyle inside each of your components

The components may seem strange with a style link, but it actually works.

render() {
  return (
    <Host>
      <link rel="stylesheet" href="/build/my-app.css" />
      RENDER THIS COMPONENT WITH GLOBAL STYLES
    </Host>
  );
}
michaeljsalo
  • 523
  • 4
  • 16