How to apply custom css to shadow DOM inside elements?

核能气质少年 提交于 2021-01-04 06:49:46

问题


I have created a new project with IONIC 4. Everything is fine and working. But when I tried to apply CSS to elements which are present inside #shadow-root.

Below is my HTML code

<ion-item class="itm-pad" no-padding>
<p>Rajkumar</p>
<ion-buttons slot="start">
  <ion-button>
    <ion-icon slot="icon-only" name="funnel"></ion-icon>
  </ion-button>
</ion-buttons>
<ion-buttons slot="end">
  <ion-button>
    <ion-icon slot="icon-only" name="search"></ion-icon>
  </ion-button>
</ion-buttons>
</ion-item>

Please refer below screenshot for this statement. Here I can apply CSS to ion-buttons and p tag as usual. But cannot apply CSS to item-native and item-inner which is inside item-native.

I have searched this issue but all said why this is implemented and how important this is. But no one explained the exact process of applying the CSS to these elements. Please check and let me know the solution.


回答1:


This is the power and pain of shadowDOM.

ShadoDOM was created to allow a sandbox of HTML and CSS.

This means that if you are going to place some HTML in a shadowDOM then you also need to place the CSS in that same shadowDOM. If you plan to have multi-layered shadowDOM then you need to place the required CSS in each layer.

<my-el>
  #shadowRoot
  // Styles must go here
  <inner-el>
    #shadowRoot
    // styles must also go here
    <ion-button>
      <ion-icon slot="icon-only" name="search"></ion-icon>
    </ion-button>
  </inner-el>
  <ion-button>
    <ion-icon slot="icon-only" name="search"></ion-icon>
  </ion-button>
</my-el>

In the example above, since shadowDOM is a sandbox, we need to place the customization if <ion-button> inside each shadowRoot/shadowDOM.

The easiest way to do this is to use the <link> tag. Create a CSS file that only defines how you want your <ion-button> to look and then add <link href="pathToCss" rel="stylesheet"> into each shadowDom.

While we may wish there were a simpler way, until the spec changes, this is the simplest way to get your inner elements properly styled.



来源:https://stackoverflow.com/questions/54907742/how-to-apply-custom-css-to-shadow-dom-inside-elements

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