CSS selector for shadow root or all top level elements in shadow root

走远了吗. 提交于 2019-12-02 10:19:21

问题


I need a selector for usage in css inside a shadow root, which selects all children (but not grand children) of the shadow root, no matter what tag they are and without giving them an ID.

In the example below, SPAN,A,P and DIV should get a red border, but SPAN IN DIV not.

<my-element>
  #shadow-root
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :root>*{border:1px red solid;}
    </style>
</my-element>

I hoped, the :root-Selector would do the job inside of a shadow dom, but thats not the case.

It would also be a possible solution if someone shows how to set an ID on the shadow root.

Update:

Tried using #shadow-root > * as selector:

seems not to work. Probably it is just google chrome developer tools visualizing the shadow root element like that.


回答1:


Use this selector: :host > *

The :host selector is described in https://drafts.csswg.org/css-scoping/#host-selector

document.querySelector( 'my-element' )
  .attachShadow( { mode: 'open' } )
  .innerHTML = `
    <span>SPAN</span>
    <a>A</a>
    <p>P</p>
    <div>
      DIV
      <span>SPAN IN DIV</span>
    </div>
    <style>
      :host>*{border:1px red solid;}
    </style>`
<my-element>
</my-element>

:host may also hold a compound selector, which must be places in brackets. E.g. :host([foo=bar]) selects a host element which has attribute foo set to bar.



来源:https://stackoverflow.com/questions/42627939/css-selector-for-shadow-root-or-all-top-level-elements-in-shadow-root

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