Back to the article · Zurück zum Artikel (Deutsch)
Example 11: ::slotted, custom property and ::part
Rule 5: Don't style the slot
Three tools for everything inheritance does not cover. The page CSS is in the <style> in the <head> of this file. The bold word also contains a <b>, to show that ::slotted(strong) only matches the direct child.
How to try it
- Look at the live example below the output boxes.
- The bold word has a gold background, set by
::slotted(strong)from inside the shadow tree. The<b>inside it is not matched by that rule. - To see that the page wins: in the developer tools, open the Elements (Inspector) panel, find the
<style>of this page's demo and addstrong { background: white; }. The gold disappears, because a rule from the page beats::slotted()for the same property. - The box has a light blue background (
--alert-bgfrom the page) and a dark blue border (::part(box)from the page). - To check: in the same
<style>, remove the--alert-bgdeclaration, the background then turns pink (fallback#fee).
console.log() and errors on this page, the same text as in the developer toolsLive example
Source
<style>
my-alert {
--alert-bg: #eef;
}
my-alert::part(box) {
border: 2px solid navy;
}
</style>
<my-alert
><strong>Warning: <b>the build</b></strong> is still running.</my-alert
>
<script type="module">
class MyAlert extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' }).innerHTML = `
<style>
.box { padding: 1rem; background: var(--alert-bg, #fee); color: darkred; }
::slotted(strong) { background: gold; }
</style>
<div class="box" part="box"><slot></slot></div>
`;
}
}
customElements.define('my-alert', MyAlert);
</script>