(SO) Styling (slotted) elements

by Danny Engelman

HTML

<!-- these spans are in lightdom, so can be styled with global CSS -->
<e-lement><span slot="oneword" class="lightdom">Hello</span></e-lement>
<e-lement><span slot="oneword" class="lightdom">Hello</span></e-lement>
<e-lement class="myclass"><span slot="oneword">World</span></e-lement>
<p>
Note: ::slotted only styles the first level ('skin') of slotted content! It can not target/style nested HTML tags
</p>
<!-- slot content is injected in the template -->
<template id='E-LEMENT'>
  <style>
    * {
      font-size: 3rem;
    }
    :host {
      display: inline-block;      /* make it all display on one line*/
      color: orange;
    }
    :host(.myclass){              /* myclass on <e-element> */
      color:hotpink;
    }
    :host(:not(.myclass)){              /* myclass on <e-element> */
      color:pink;
    }
    :host(:hover) {
      color: lightgreen;
    }
    :host(:active:active) {      /* click/select element. Higher Specificity than :hover*/
      color: yellow;
    }
    .container {
      background: teal;
    }
    ::slotted(*) {
      border: 3px solid lightcoral;
      color: blue;      /* only applied when color is not applied in Global CSS (higher Specificity)*/
      background: var(--slottedbackground) /* shadowDOM can read ALL inherited CSS variables */
    }
    ::slotted(.lightdom) {
      background: whitesmoke;
    }
    ::slotted(*)::after {
      color: red !important;      /* applied !important overrules global CSS Specificity */
    }
    [name="oneword"]:not(:active) {
      text-transform: uppercase;
    }
  </style>
  <div class="container">word:<slot name="oneword"></slot>
  </div>
</template>
<style id="applystyle"></style>

CSS

body {
  background: lightgrey;
  font-size: 3em;
  --slottedbackground: gold;
  /* global property propagating to ALL shadowDOMs */
}

/* styling elements in light DOM */
.lightdom {
  color: green;
}

[slot="oneword"]::after {
  content: "!!";
  color: black;  /* overruled with !important inside my-element style */
}

[slot="oneword"] {
  text-decoration: underline;
}


/* no! these are in shadowDOM, can't style them with global CSS */
.container {
  background: white;
}
[name="oneword"] {
  color: red !important;
}

JavaScript

class Element extends HTMLElement {
  constructor() {
    super();
    let template = document.getElementById(this.nodeName);
    this.attachShadow({
      mode: 'open'
    }).append(template.content.cloneNode(true));
  }
}
window.customElements.define('e-lement', Element);
//applystyle.innerHTML='.lightdom{ color: black;}';//global CSS styles slotted *content*