<ul>
<li><b>Task</b>: Style "slotted" <i>are great!</i> background Gold, **without** affecting ANYTHING else on the page</li>
<li><b>Problem:</b> The <span> is styled from its *container* (global) CSS, NOT from shadowDOM CSS</li>
<li><b>Requirement:</b> Set styles in the same Web Component TEMPLATE </li>
<li><b>Solution:</b> Add a *extra* shadowRoot boundary</li>
</ul>
<style id="GlobalStyle">
body { font: 12px Arial /* inheritable styles are applied to all components */ }
h1 { color: blue }
span { color: red }
</style>
<H1>Web Components<span> are something different</span></H1>
<component-with-slots>
<!-- ALL Nodes here in lightDOM are MOVED to a NEW DIV WITH an extra shadowDOM! -->
<H1 slot="title">Web Components <span>are great!</span></H1>
Yes, they are!!!
<span>::slotted(span) does <span>NOT</span> style the span in H1</span>
<span>H1 *inside* the Component is now inside a shadowRoot, so not styled by global CSS</span>
<span><slot> are styled <b>with their own <style></b> IN the TEMPLATE</span>
</component-with-slots>
<TEMPLATE id="COMPONENT-WITH-SLOTS">
<style>
:host{ font: 16px Verdana }
::slotted(span) {
/*
H1 is REFLECTED to <slot name="title">
all other lightDOM content is REFLECTED to the default <slot>
::slotted, a simple selector, can only style the 'skin', not contents
*/
background: lightgreen !important; /* selector in lightDOM has higher Specificity */
color: firebrick;
display: block;
padding: .5em;
}
</style>
<slot name=title></slot>
<slot><!-- DIV *content* will be REFLECTED here --></slot>
<!-- style element is MOVED UP to NEW DIV parent-container lightDOM! -->
<!-- all <component-with-slots> lightDOM is also moved there !! -->
<style id="STYLE-LIGHTDOM">
span { background: grey }
[slot="title"] span { background: gold }
</style>
</TEMPLATE>
<script>
customElements.define('component-with-slots',...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!