๐ธslotted nodes
a.k.a distributed nodes.
web โฉ component โฉ slot โฉ slotted nodes
Styling in Shadow DOM โฉ ::slotted()
Only custom element's top-level children (in the light DOM) may have
[slot]
attributeโ๏ธ ๐ See "light DOM" tab in example code in Using Slots.::slotted() only select slotted element itself, not its descendants (content)โ๏ธ
Slotted Contents
slotted content come from light DOM, they use document stylesโ๏ธ
shadow DOM styles do not affect slotted contentโ๏ธ
::slotted() only select slotted element itself, not its descendants (content)โ๏ธ
::slotted() can't go inside light DOM, for example: ::slotted(div) p is invalidโ๏ธ
::slotted() can't be used in .querySelector()โ๏ธ
ๅจไธ้ข็็ฏไพ็ขผไธญ๏ผๆๅๅๅฅๅจๅค้จๅๅ
ง้จ CSS ๅฐ <span>
ๅ
็ด ๅใ็ฒ้ซใ่ใ็ด
่ฒใๆ ผๅผ่จญๅฎ๏ผๅฐๆผๆๅ
ฅ shadow DOM<slot>
็ <span>
่่จ๏ผๅชๆๅค้จ็ใ็ฒ้ซใ่จญๅฎๆๆ (๐ see: "codepen" tab below)ใ ๐พ replit
<!-- โญ๏ธ document (outer) styles -->
<style>
span {
font-weight: bold
}
</style>
<!-- โญ๏ธ custom element -->
<user-card>
<!-- โญ๏ธ slotted element -->
<div slot="username">
<!--
โญ๏ธ slotted content is affected by document (outer) styles,
not by local (shadow DOM) stylesโ๏ธ
-->
<span>John Smith</span>
</div>
</user-card>
<script>
customElements.define('user-card', class extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'});
// โญ๏ธ shadow tree (with named <slot>)
// 1. slotted elements come from light DOM, they use document styles.
// 2. local styles do not affect slotted content.
this.shadowRoot.innerHTML = `
<style>
span { background: red; }
</style>
Name: <slot name="username"></slot>
`;
}
});
</script>
Styling Slotted Content
๐พ ::slotted() lab
use document (outer) styles (in light DOM).
style <slot> (in shadow DOM) and rely on CSS inheritance.
use ::slotted(ยซselectorยป) in shadow DOM.
Last updated
Was this helpful?