'How do I use Tippy in shadow DOM with scoped CSS?
I want to use Tippy.js in my shadow DOM.
Since scripts can access my shadow DOM but styles can't, I tried to inline the Tippy CSS within the shadow DOM and link Popper's and Tippy's JS outside. Here is a demo of it not working.
I need the CSS to be scoped so I have the following constraint:
<style>
:host {
all: initial; /* 1st rule so subsequent properties are reset. */
display: block;
contain: content; /* Boom. CSS containment FTW. */
/* any other CSS, so this is where I inlined the Tippy's */
}
</style>
Solution 1:[1]
Get the target element, create a style tag to hold the inline CSS and append the style tag as a child.
const anchor = document.querySelector('#blog-header')
const style = document.createElement('style')
style.type = 'text/css'
const stylesheet = // inline Tippy.js CSS here or fetch it from somewhere else
style.appendChild(document.createTextNode(stylesheet))
anchor.content.prepend(style)
Solution 2:[2]
For people getting here from google and wandering what's the current process for putting tippy into shadow dom (e.g. for using with browser extension). The following works for me:
const shadowRoot = initShadowRoot()
function initShadowRoot() {
const shadowContainer = document.createElement("div")
const shadowRoot = shadowContainer.attachShadow({mode: "open"})
let style = document.createElement('style')
style.innerText = shadowCss // inline or use a bundler to give you a string representation
shadowRoot.appendChild(style)
document.body.appendChild(shadowContainer)
return shadowRoot
}
//---
//elsewhere when initializing tippy:
tippy(elment, {
// ...
// in shadow dom to avoid affecting the page styles
appendTo: () => shadowRoot,
//...
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Stvad |
