Shadow Dom inheriting parent page CSS [Chrome] [duplicate]

半城伤御伤魂 提交于 2020-11-29 04:29:45

问题


Everything I've read indicates that the Shadow Dom is supposed to be 'safe' from its parent page CSS. I.E. if I have all divs styled to have purple font:

<style>
  div{color: purple}
</style>

The divs in my Shadow Dom should have the browser default color.

I am writing a chrome extension that injects html into any given page. Unless this html is protected by either Shadow Dom or Iframe, it will inherit all the page's CSS.

The advice to solve this problem in this question, was to use the Shadow Dom. So I implemented a solution, but noticed it was inheriting the page's CSS still. I thought this might have been an issue with using it in a Chrome extension, so I hijacked a jsBin from some Shadow Dom examples (and threw it in another live coding app for good measure).

https://codepen.io/hyrumwhite/pen/xPRexQ

Same result. My shadow DOM inherits the page CSS, and my divs (and weirdly my h1) are purple.

It looks like the children in the Shadow Dom will inherit any styling applied to the host element.

Is this working as designed? Is there a way to prevent this? Or is the shadow DOM new enough that this is a bug and I should expect similar bugs as I keep using it?


回答1:


Inherited properties will be inherited as usual. It's better to think of the shadow boundary as affecting the cascade, namely the scope of selectors and the importance of rules.

To isolate shadow content from the page, consider the all property.

document.getElementById("example_control").attachShadow({mode:'open'}).innerHTML=`
  <h1>shadow dom header</h1>
  <div>shadow dom div</div>`;
document.getElementById("example_initial").attachShadow({mode:'open'}).innerHTML=`
  <style>*{all:initial}</style>
  <h1>shadow dom header</h1>
  <div>shadow dom div</div>`;
document.getElementById("example_unset").attachShadow({mode:'open'}).innerHTML=`
  <style>*{all:unset}</style>
  <h1>shadow dom header</h1>
  <div>shadow dom div</div>`;
div{color:purple}
div{border:1px solid}
<p>control:
<div id=example_control></div>

<p>initial:
<div id=example_initial></div>

<p>unset
<div id=example_unset></div>



回答2:


For me, adding :host { all: initial } as the first CSS rule within the ShadowDOM styles prevented inheritance without affecting other CSS defined within the ShadowDOM.

Using * { all: initial } proved to be too broad and overrode most of my CSS defined within the ShadowDOM.

Ref: Section marked #reset in WebFundamentals project ShadowDOM document.



来源:https://stackoverflow.com/questions/47189985/shadow-dom-inheriting-parent-page-css-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!