Inject css into ShadowDOM (WC)
The big mystery of using a css-framework with shadowDOM...
Kinda simple solution, but it works, just tag your link/style-tags with "data-inject"-attribute.
Example below.
HTML
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" data-inject>
<style data-inject>
body {
display: grid;
height: 100vh;
}
.wrapper {
border: 1px solid #333;
border-radius: 5px;
padding: 1rem 3rem;
margin: auto;
text-align: center;
}
</style>
<div class="wrapper">
<h1>Inject styles into webcomponents</h1>
<p>Inject tags into shadowDOM by prefix with data-inject,<br>
realy nice when using a css-framework like bootstrap.</p>
<hr>
<h3>Normal button regular DOM</h3>
<button class="btn btn-primary">Test</button>
<hr>
<h3>Button inside webcomponent with ShadowDOM</h3>
<my-btn title="Test"></my-btn>
</div>
JS
class MyButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.injections = Array.from(
document.querySelectorAll("[data-inject]")
).map((el) => el.outerHTML);
}
connectedCallback() {
const title = this.getAttribute("title");
this.shadowRoot.innerHTML = `
${this.injections.join("\n")}
<div class="button-wrapper">
<button class="btn btn-primary">${title}</button>
</div>
`;
}
}
customElements.define("my-btn", MyButton);