最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to stop inheriting CSS within shadowDom from HTML tag? - Stack Overflow

programmeradmin1浏览0评论

Im injecting some Javascript that creates an isolated div located at the top of the body. Within this div there is a shadowDom element. The reason I went with shadowDom is because I thought it stoped CSS from bleeding in to all the divs within the shadowDom. But I can clearly see that it is inheriting style from the tag(font-size: 62.5%;). This is causing my text to be smaller. I can override this with adding font-size: 100% !Important but even though it crosses it out in the inspector tools it does not actually change. The only way I can get it to work is by unchecking the box in the CSS portion.

Please Help

Thanks,

Dev Joe

HTML Shadow Dom IMAGE

CSS Checked IMAGE

CSS Unchecked IMAGE

Im injecting some Javascript that creates an isolated div located at the top of the body. Within this div there is a shadowDom element. The reason I went with shadowDom is because I thought it stoped CSS from bleeding in to all the divs within the shadowDom. But I can clearly see that it is inheriting style from the tag(font-size: 62.5%;). This is causing my text to be smaller. I can override this with adding font-size: 100% !Important but even though it crosses it out in the inspector tools it does not actually change. The only way I can get it to work is by unchecking the box in the CSS portion.

Please Help

Thanks,

Dev Joe

HTML Shadow Dom IMAGE

CSS Checked IMAGE

CSS Unchecked IMAGE

Share Improve this question edited Dec 6, 2019 at 12:39 Supersharp 31.2k11 gold badges102 silver badges147 bronze badges asked Dec 5, 2019 at 14:27 Joseph LezcanoJoseph Lezcano 671 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You should not use a relative font size (like 100%) because it applies to inherited size... so this will have no effect.

Insead, you should define a rule to the :host CSS peudo-class:

:host {
   font-size: initial ;
}

NB: You'll need to add !important only if the font-size defined in the container (the main document) applies to the host element directly.

NB #2: You can use all: initial instead but you cannot bine it with !important.

host.attachShadow( { mode: 'open' } )
    .innerHTML = `
      <style>
        :host { all: initial }
      </style>
      Inside Shadow Root <br>
      <div>Div in Shadow DOM</div>
      <slot></slot>
    `
body { font-size : 62.5% ; color: red }
Small Font
<div>Div in main Document</div>
<div id=host>Light DOM</div>

No need for shadow dom, just use the all attribute to disable the inheritance.

#myElement {
  all: initial;
}
发布评论

评论列表(0)

  1. 暂无评论