5

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
  • 21,969
  • 32
  • 147
  • 289

1 Answers1

8

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 = (name) => document.getElementById(name)
                                       .content.cloneNode(true);
      super()
       .attachShadow({ mode: 'open' })  
       .append(  template(this.nodeName)  );
    }
  })
<template id="MY-TABLE">
  <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/WebComponents/108ey7b2/


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

Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
  • 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
  • 1
    ``::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