shadow DOM styles
Google ⟩
Web Component ⟩ Component-defined styles
if an element has shadow DOM, then its light DOM is not displayed.
styles defined beneath a shadow root are private to that tree and will never affect the light DOM elements on the outside.
shadow root can define default styles for its host element, but these will be overridden by light DOM styles.
📗 CSSTrick ⟩ contain
:host, :host(), :host-context(), ::slotted()
:host, :host(), :host-context() only works in the context of a shadow root, you can't use it outside of shadow DOM.
/* ⭐️ select host element (from inside shadow DOM) */
:host {
/* ⭐️ by default, custom elements are `display: inline` */
display: block;
/* CSS containment */
contain: content;
}
:host {
opacity: 0.4;
will-change: opacity;
transition: opacity 300ms ease-in-out;
}
/*
⭐️ :host(<selector>) ⭐️
-----------------
target the host if it matches a <selector>.
*/
:host(:hover) {
opacity: 1;
}
:host([disabled]) { /* style when host has disabled attribute. */
background: grey;
pointer-events: none;
opacity: 0.4;
}
:host(.blue) {
color: blue; /* color host when it has class="blue" */
}
:host(.pink) > #tabs {
color: pink; /* color internal #tabs node when host has class="pink". */
}<body class="darktheme">
<fancy-tabs>
...
</fancy-tabs>
</body>
/*
⭐️ :host-context(<selector>) ⭐️
-------------------------
select host if it or any of its ancestors matches <selector>.
*/
:host-context(.darktheme) {
color: white;
background: black;
}/*
⭐️ won't select text node placed into slot (only elements)
*/
/* selects any element placed inside a slot */
::slotted(*) {
font-weight: bold;
}
/* selects any <span> placed inside a slot */
::slotted(span) {
font-weight: bold;
}Topics
Examples
:host - <custom-dialog>, <user-card>, <element-details>
:host() - <custom-dialog>, <element-details>
::slotted() - <user-card>, <element-details> 👉 slotted content
Last updated
Was this helpful?