'Preact in the Shadow DOM but lost all styles
I'm building a widget and hence wanted to load the widget Preact app in the shadow DOM to avoid CSS conflicts.
I am succesfully able to do so like this.
const host = document.querySelector('#widget-_hw');
const shadow = host?.attachShadow({ mode: 'open' });
const renderIn = document.createElement('div');
shadow?.appendChild(renderIn);
render(h(App, { ...config, element: el }), renderIn)
But lost all styles.
I have all styles required for Widget inside a file called main.css. Where I have all styles defined like this
reset {
composes: scope;
background: var(--color-bg);
color: var(--color-text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
margin: 0;
}
.reset h1,
.reset h2,
.reset h3,
.reset h4,
.reset h5,
.reset h6 {
line-height: var(--line-height);
}
//and many other like button, input fields, containers etc
Could someone suggest me a way to import style elements back into the preact app?
Solution 1:[1]
The whole point of shadowDOM is to NOT be styled by global/outside CSS
ShadowDOM is styled by:
<style>within shadowDOMInheritable styles
https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/(cascading) CSS properties
shadowParts (and Themes)
https://meowni.ca/posts/part-theme-explainer/<slot>are reflected, they are NOT styled by the shadowDOM, but by its container.
See: ::slotted content(feb 2022) Constructible StyleSheets is still a Chromium only party
https://caniuse.com/mdn-api_cssstylesheet_cssstylesheetyour custom directive
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Danny '365CSI' Engelman |
