Use CSS selectors like :first-child inside shadow dom

后端 未结 2 1381
无人共我
无人共我 2021-01-26 15:20

Is there any way to use css selectors like :first-child, :not(:last-child) inside of the shadow dom?

The example is like this

CustomElement.html

         


        
2条回答
  •  臣服心动
    2021-01-26 15:39

    The same answer as I gave in your question yesterday

    Slotted content is not moved to shadowDOM,

    it remains (invisible) in lightDOM

    and is REFLECTED in the shadowDOM

    So SLOTTED content styling is done in the CSS scope where resides.

    or with ::slotted( x )

    From the docs:

    ::slotted can only take a compound selector (in the parenthesis). The reason of this > restriction is to make a selector style-engine friendly, in terms of performance.

    So with your structure you can do:

     ::slotted(.heading) { }
    or
     ::slotted(:first-child) { }
    

    but not:

     ::slotted(.heading:first-child)
    

    Because it is a complex selector, not a (simple) compound selector

    So your headings can be styled in global CSS, and will REFLECT to slotted content:

    my-element div.heading{
      background:blue;
      color:white;
    }
    

    If you want to encapsulate this styling you have to wrap everything in (another) component

    You can target all UNnamed slotted content with:

        ::slotted(:not([slot])){
          font-weight:bold;
        }
    

    Here is another JSFiddle to play with slotted styling:

    https://jsfiddle.net/CustomElementsExamples/whtjen3k/

提交回复
热议问题