4

I have a web component that has a template which looks like this...

<template>
  <div class="jrg-app-header">
    <slot name="jrg-app-header-1"></slot>
    <slot name="jrg-app-header-2"></slot>
    <slot name="jrg-app-header-3"></slot>
  </div>
</template>

I am basically trying to set the contents of the last slot to have flex:1; in style. Is there a CSS query that will do this? I tried something list

::slotted(*):last-child{
  flex:1;
}

But it did not work. How do I style the last slotted object?

Jackie
  • 19,725
  • 31
  • 126
  • 253

1 Answers1

5

For long answer on ::slotted see: ::slotted CSS selector for nested children in shadowDOM slot


From the docs: https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

::slotted( <compound-selector-list> )

The pseudo selector goes inside the brackets: ::slotted(*:last-child)

Note: :slotted(...) takes a simple selector
See (very) long read: ::slotted CSS selector for nested children in shadowDOM slot

  customElements.define('my-table', class extends HTMLElement {
    constructor() {
      let template = document.cloneNode(document.querySelector('#t1').content, true);
      super()
       .attachShadow({ mode: 'open' })  
       .append(template);
    }
  })
<template id="t1">
  <style>
    :host {
      display: flex;
      padding:1em;
    }
    ::slotted(*:first-child) {
      background: green;
    }
    ::slotted(*:last-child) {
      background: yellow;
      flex:1;
    }
    ::slotted(*:first-of-type) {
      border: 2px solid red;
    }
    ::slotted(*:last-of-type) {
      border: 2px dashed red;
    }
  </style>
  <slot name="column"></slot>
</template>

<my-table>
  <div slot="column">Alpha</div><div slot="column">Bravo</div><div slot="column">Charlie</div>
</my-table>
<my-table>
  <div slot="column">Delta</div><div slot="column">Echo</div>
</my-table>

JSFiddle playground: https://jsfiddle.net/CustomElementsExamples/whtjen3k/


More SLOT related answers can be found with StackOverflow Search: Custom Elements SLOTs

Danny '365CSI' Engelman
  • 11,626
  • 1
  • 22
  • 35
  • Thanks but on a side note what about :before and :after? I tried... ::slotted(*:before) and ::slotted(*):before – Jackie Dec 31 '19 at 01:55
  • ``::slotted()`` requires a **simple** CSS selector between the round brackets( ) ``:before`` by itself is not a valid selector, neither is *nothing* So ``::slotted(*):before`` will work. The W3C debate was here: https://github.com/w3c/webcomponents/issues/655 It is not easy to explain; you learn by reading all the SO slotted answers: https://www.google.com/search?q=stackoverflow+custom+elements+slotted&as_qdr=y1 (filtered SO 'slotted' Google results by last year with &as_qdr=y1) – Danny '365CSI' Engelman Dec 31 '19 at 10:50