问题
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