::slotted() CSS Pseudo Element
Description
The CSS ::slotted()
pseudo element allows you to style the elements that are placed inside of a slot element. Slots are used to distribute content inside of a web component.
The ::slotted()
pseudo element can only be used inside of a shadow DOM. To use ::slotted()
, you would first need to create a template element and a custom element. The template element would contain the slot element, and the custom element would contain the template element.
Once you have created the template element and the custom element, you can start styling the elements that are placed inside of the slot element. To do this, you would use the ::slotted()
pseudo element in the CSS for the custom element.
Syntax
::slotted(<compound-selector>) { /* ... */ }
Example
<template id="card-template">
<div>
<h2><slot name="caption">title goes here</slot></h2>
<slot name="content">content goes here</slot>
</div>
</template>
<my-card>
<span slot="caption">Error</span>
<p class="content" slot="content">Build failed!</p>
</my-card>
<script>
customElements.define(
'my-card',
class extends HTMLElement {
constructor() {
super();
const template = document.getElementById('card-template');
const shadow = this.attachShadow({ mode: 'open' });
shadow.appendChild(template.content.cloneNode(true));
const elementStyle = document.createElement('style');
elementStyle.textContent = `
div {
width: 200px;
border: 2px dotted red;
border-radius: 4px;
}`;
shadow.appendChild(elementStyle);
const cssTab = document.querySelector('#css-output');
const editorStyle = document.createElement('style');
editorStyle.textContent = cssTab.textContent;
shadow.appendChild(editorStyle);
cssTab.addEventListener('change', () => {
editorStyle.textContent = cssTab.textContent;
});
}
},
);
</script>
/* This CSS is being applied inside the shadow DOM. */
::slotted(.content) {
background-color: aqua;
}
h2 ::slotted(span) {
background: silver;
}
Notes
In CSS3, pseudo-elements were denoted by two colons to make the syntax different from pseudo-classes. In CSS2, they are indicated by a single colon. Browsers generally understand both syntaxes.
Browser Support
The following table will show you the current browser support for the CSS ::slotted()
pseudo element.
Desktop | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
|
79 | 50 | 63 | 37 | 10 |
Tablets / Mobile | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
50 | 63 | 37 | 10 | 5 | 50 |
Last updated by CSSPortal on: 1st October 2023