2

As pointed out here:

Because of the isolation of styles, which is a feature of Shadow DOM, you cannot define a global CSS rule that will be applied in the Shadow DOM scope.

Is there any way to define simple CSS classes globally in some global styles.css file (for example) that we can use in all kinds of places and re-use them in individual components?

Currently, the simple answer would be to add a corresponding <link href="styles.css"> tag to every single component that we define. This has been proposed here to allow web components use bootstrap classes, and again here to support ionic. Is that a good approach? Would that not be terrible performance-wise, if we included big styles.css in tens or hundreds of components?

Eugene
  • 10,957
  • 20
  • 69
  • 97
Domi
  • 22,151
  • 15
  • 92
  • 122

2 Answers2

1

Constructable Stylesheets are a proposal to solve exactly that problem.

In a nutshell, it's a way to share the same stylesheet across components without requesting the stylesheet each time. Currently it's Chrome only, but there is a polyfill, and, Firefox at least, seem to support this proposal.

lamplightdev
  • 2,041
  • 1
  • 20
  • 24
0

Maybe it could help you. From this link https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM

You have the following:

Internal versus external styles

In the above example we apply style to the Shadow DOM using a element, but it is perfectly possible to do it by referencing an external stylesheet from a element instead.

For example, take a look at this code from our popup-info-box-external-stylesheet example (see the source code):

// Apply external styles to the shadow dom
const linkElem = document.createElement('link');
linkElem.setAttribute('rel', 'stylesheet');
linkElem.setAttribute('href', 'style.css');

// Attach the created element to the shadow dom
shadow.appendChild(linkElem);

Note that elements do not block paint of the shadow root, so there may be a flash of unstyled content (FOUC) while the stylesheet loads.

Many modern browsers implement an optimization for tags either cloned from a common node or that have identical text, to allow them to share a single backing stylesheet. With this optimization the performance of external and internal styles should be similar.

To make it as independent and modular as possible, I would propose something like that:

let myStyles = querySelector('rel[href="style.css"]');
shadowDOM.appendChild(myStyles);

Normally, you don't have another option except of adding the styles directly to the shadow DOM.