1

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>
Flo
  • 65
  • 1
  • 9

2 Answers2

1

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,
    //...
})

Stvad
  • 360
  • 2
  • 17
0

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)
herodrigues
  • 948
  • 1
  • 7
  • 11
  • I tried that but doesnt seem to work still. think the style needs to be within ":host" in the shadow DOM style. https://codepen.io/anon/pen/ErExqd – Flo Feb 17 '19 at 20:36
  • yes, if there's global font to be inserted, they need to live outside the shadow DOM. I haven't work with Tippy.js, so I don't know if there are fonts included in their stylesheet, – herodrigues Feb 17 '19 at 21:52