In the Shadow DOM <style>
tag, you can apply CSS styles directly to the <slot>
element as @admcfajn suggeded in its second comment:
slot[name="thing"] { .. }
But if you want to target an element from the light DOM when it's inserted in the Shadow DOM through a <slot>
element, you should use the ::slotted(
) pseudo-element function.
::slotted( div[slot="thing"] ) { color: green }
will color in red the text inside the <div>
with the attribute slot="name"
.
Important: the second solution is preferred, because the CSS from the light DOM has priority. Thereforce style inherited from the light DOM will override style from the slot element. See the example with background-color
below:
customElements.define( 'custom-element', class extends HTMLElement {
constructor() {
super()
this.attachShadow( { mode: 'open' } ).innerHTML = tpl.innerHTML
}
} )
body { background-color: lightblue }
<template id=tpl>
<style>
::slotted( [slot=thing] ) { background-color: green }
slot[name="other"] { background-color: red }
</style>
<slot name="thing"></slot>
<slot name="other"></slot>
</template>
<custom-element>
<div slot="thing"> <div>Thing 1 </div></div>
<div slot="thing"> Thing 2 </div>
<div slot="other"> Thing 3 </div>
</custom-element>
[slot="thing"]{ border: 2px dashed #f00; }
Attribute selectors – Knowhow:head[slot="thing"]
given shadow dom? – Oddmentslot[name="thing"]
maybe? – Knowhow:defined
,[slot=...]
, and for the CSS inside the component,:host
,::slotted()
,slot[name=...]
. – Hitormiss