::slotted

by WebComponents

HTML

<ul>
  <li><b>Task</b>: Style "slotted" <i>are great!</i> background Gold, **without** affecting ANYTHING else on the page</li>
  <li><b>Problem:</b> The &lt;span> is styled from its *container* (global) CSS, NOT from shadowDOM CSS</li>
  <li><b>Requirement:</b> Set styles in the same Web Component TEMPLATE </li>
  <li><b>Solution:</b> Add a *extra* shadowRoot boundary</li>
</ul>

<style id="GlobalStyle">
  body { font: 12px Arial /* inheritable styles are applied to all components */ }
  h1   { color: blue }
  span { color: red }
</style>

<H1>Web Components<span> are something different</span></H1>

<component-with-slots>
  <!-- ALL Nodes here in lightDOM are MOVED to a NEW DIV WITH an extra shadowDOM! -->
  <H1 slot="title">Web Components <span>are great!</span></H1>
   Yes, they are!!! 
  <span>::slotted(span) does <span>NOT</span> style the span in H1</span>
  <span>H1 *inside* the Component is now inside a shadowRoot, so not styled by global CSS</span>
  <span>&lt;slot> are styled <b>with their own &lt;style></b> IN the TEMPLATE</span>
</component-with-slots>

<TEMPLATE id="COMPONENT-WITH-SLOTS">
  <style>
    :host{ font: 16px Verdana }
    ::slotted(span) {
      /*
        H1 is REFLECTED to <slot name="title">
        all other lightDOM content is REFLECTED to the default <slot>
        ::slotted, a simple selector, can only style the 'skin', not contents
      */
      background: lightgreen !important; /* selector in lightDOM has higher Specificity */
      color: firebrick;
      display: block;
      padding: .5em;
    }
  </style>
  <slot name=title></slot>
  <slot><!-- DIV *content* will be REFLECTED here --></slot>
  
  <!-- style element is MOVED UP to NEW DIV parent-container lightDOM!  -->
  <!-- all <component-with-slots> lightDOM is also moved there !! -->
  <style id="STYLE-LIGHTDOM">
    span { background: grey }
    [slot="title"] span { background: gold }
  </style>

</TEMPLATE>

<script>
  customElements.define('component-with-slots',...