skip to content
dz

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

  1. Look at the live example below the output boxes.
  2. 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.
  3. To see that the page wins: in the developer tools, open the Elements (Inspector) panel, find the <style> of this page's demo and add strong { background: white; }. The gold disappears, because a rule from the page beats ::slotted() for the same property.
  4. The box has a light blue background (--alert-bg from the page) and a dark blue border (::part(box) from the page).
  5. To check: in the same <style>, remove the --alert-bg declaration, the background then turns pink (fallback #fee).
Console output mirrored from console.log() and errors on this page, the same text as in the developer tools

Live example

Warning: the build is still running.

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>