简体   繁体   中英

Apply CSS styles to Light DOM (shadow DOM) in custom element HTML5

I have read all the documentation about web components and according to the standards it is not possible to apply isolated CSS styles (shadow) to the elements that the user enters inside a custom element (light DOM), that is, the content that the user adds within a slot element, an example below:

<! - Custom element ->
    <index-book>
     <slot>

       <! - Light DOM here / This content was introduced by the user ->
       <div class = "container">
         <span class = "section"> Section title ... </ span>
         <ul class = "sections">
           <li> ... </ li>
           <li> ... </ li>
           <li> ... </ li>
         </ ul>
       </ div>

     </ slot>
    </ index-book>

In fact, making use of the pseudo-element class of CSS ::slotted () could apply styles only to the first direct child of the slot element, that is, to div.container , but not to its children.

I have reached two conclusions, or if you can apply Shadow styles to the entire structure of elements of the DOM light and I do not know how, or the second option is that the user should not be allowed to enter content into a slot that has multi -level as in the previous example, div within div ...

If the correct answer is the second one, how should I do so that the user inserts content within the custom element and the final result is the same or similar to the example shown above (trying to create a custom book index element) and can apply isolated styles in the DOM tree of the custom element.

I must mention that I am not using Polymer or any other library to develop this custom element.

Thank you very much!

According to web fundamentals :

<name-badge>
  <h2>Eric Bidelman</h2>
  <span class="title">
    Digital Jedi, <span class="company">Google</span>
  </span>
</name-badge>

<style>
::slotted(h2) {
  margin: 0;
  font-weight: 300;
  color: red;
}
::slotted(.title) {
   color: orange;
}
/* DOESN'T WORK (can only select top-level nodes).
::slotted(.company),
::slotted(.title .company) {
  text-transform: uppercase;
}
*/
</style>
<slot></slot>

So I guess you're out of luck here.

However if it's light dom maybe you could style it directly or wrap it in another custom element?

Why not use use normal CSS, that is bundled with your web component file, but applies to the normal dom instead of the shadowDOM, eg

<style>
index-book.container {
    color: red;
}
index-book.sections{
    color: blue;
}

/* or */
index-book > div {
    color: red;
}
</style>

Since these styles beging with the custom web component name, they will not apply to any other elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM