Unable to select <slot> using CSS Selector, how to style it to make "Launch" text color red?

234 Views Asked by At

As per above screenshot, I am trying to style web component , and content inside slot reveal/pointing to "Launch" when clicked. How can I style slot to apply text colour to "Launch". I am struggling to select slot using css selector. Any help/suggestions would be helpful.

I already tried to apply style using below selector but did not work for me.

sl-tab::part(base)::slotted(*) { color: red; }

2

There are 2 best solutions below

1
On BEST ANSWER

I figured out how to style Launch with another way using:

sl-tab[active]::part(base) {
  color: red;
}
0
On

Slotted content is not moved to shadowDOM, therefor you can not style it from shadowDOM

Slotted content is reflected to shadowDOM

Slotted (lightDOM) content is styled by the container/level the lightDOM is in, in this case global CSS (see H1 and span styling)

::slotted(span) can only style the skin of lightDOM content, not DOM levels deeper (only span2 is styled)

Style slotted text with an [attribute] on the host element (see launched)

customElements.define("component-with-slot",class extends HTMLElement{
  constructor(){
    super().attachShadow({mode:"open"}).innerHTML = 
     `<style>
        *::slotted(span) { padding:2em } 
        :host([launched])  { color:red; font-weight:bold }
      </style>` +
     `<slot></slot>`;
  }
});
/* global CSS */
h1 {
  border:5px solid blue
}
span {
  border:4px dashed red;
}
<component-with-slot>
  <h1>I am slotted <span>span1</span></h1>
  <span>span2</span>
</component-with-slot>

<component-with-slot launched>
  Launch happened
</component-with-slot>

For very detailed info see: ::slotted CSS selector for nested children in shadowDOM slot