[SO] SlotMeister - Styling lightDOM in SLOTs
by WebComponents
HTML
<img src=https://i.imgur.com/0GrB8Fm.png />
See: <a href="StackOverflow: https://stackoverflow.com/questions/61626493/slotted-css-selector-for-nested-children-in-shadowdom-slot/61631668#61631668
">StackOverflow answer</a>
<!-- ========================================================== DEFINE CUSTOM ELEMENT -->
<script>
customElements.define('to-do', class extends HTMLElement {
connectedCallback() {
setTimeout(() => { // make sure we can access (light)DOM here
let template = document.getElementById(this.nodeName).content.cloneNode(true);
let div = this.attachShadow({ // create shadowDOM (1)
mode: 'open'
}).appendChild(document.createElement("div")); // add DIV container
div.attachShadow({ // attach shadowDOM to DIV container
mode: 'open'
}).append(template); /* add Template content to DIV shadowRoot */
div.append( // move to DIV lightDOM:
div.shadowRoot.querySelector('#styleslots'), // style originally from Template
...this.children // all original to-do lightDOM (this required the setTimeout!)
);
})
}
});
</script>
<!-- ========================================================== GLOBAL HTML -->
<style id="GlobalStyle">
body {
background: grey;
/* ! inherited properties trickle down into Custom Elements! */
font: 13px Arial;
color: orange;
}
span {
/* demonstrating only global spans are affected */
border: 2px dashed red;
}
to-do {
margin: 1em;
}
</style>
<h2>Styling <span>Slotted</span> Content</h2>
<!-- ========================================================== TEMPLATE -->
<template id="TO-DO">
<!--------------------------------------------- Template styling:-->
<style>
:host {
display: block;
background: lightyellow;
}
span {
/* labels Todo and When , will not style SPANs inside slotted content */
font-weight: bold;
color: black;
}
...