How to apply global css to web components through shadow-dom
Asked Answered
O

1

4

I'm working on a lit-element project, and I got a problem that reset.css cannot be applied to web components wrapped with shadow-root

I've tried this way, and I got this following error.

Refused to apply style from 'http://localhost:8080/style/static/reset.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

The code I tried is this:

<script>
  var css = new CSSStyleSheet()
  css.replace('@import url("./style/static/reset.css")')
  document.adoptedStyleSheets = [css]
</script>

this is put into a html file.

How can I avoid this error, and apply the reset.css to the web components?

Ouphe answered 2/8, 2019 at 11:41 Comment(1)
Actually it should work. The error come from somewhere else (maybe your web server that sets a wrong MIME type)Barbuto
S
2

Does it help to apply the replace import to the shadowroot as opposed to the document?

const node = document.createElement('div')
const shadow = node.attachShadow({ mode: 'open' })
shadow.adoptedStyleSheets = [sheet]

https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets

Edit -- addition for clarity:

The above addresses applying a style sheet possibly containing @import statements onto the frame to which your original question refers, the shadow-root node (element), however, because your code tries to apply the instantiated sheet to the document, to me, the question becomes a bit hazy.

The error you indicate seems indicative of code which attempts to apply a style sheet created in another document:

If you try to adopt a CSSStyleSheet that's constructed in a different Document, a "NotAllowedError" DOMException will be thrown.

https://github.com/WICG/construct-stylesheets/blob/gh-pages/explainer.md

Shluh answered 2/8, 2019 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.