Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style an ion-icon inside an ion-toast (nested shadow elements)?

I've tried multiple approaches:

  1. Set inline styles but it looks like @ionic removes style="...." attributes when generating the toast

  2. CSS variables but can't figure out how to style a nested shadow element that doesn't expose an api (ion-icon)

Currently I'm doing:

let opts = { message: '<ion-icon name="icon-name" style="font-size: 50px;...other styles..">' };
const toast = await this.toastController.create(opts);

Toasts export a named part (message) but this isn't enough since I need to make the icon bigger than the text.

ion-toast {  
  // this works
  &::part(message) {
        font-size: 1.2em;
  }      
  
  
  // None of this works and my goal is to style the ion-icon
  
  &::part(message) ion-icon {
        font-size: 1.2em;
  }      
  &::part(message) /deep/ ion-icon {
        font-size: 1.2em;
  }      

  &::part(message)::part(ion-icon) {
        font-size: 1.2em;
  }      

}

Here's how my toast looks like: enter image description here

Any thoughts?

like image 635
Lothre1 Avatar asked Jan 31 '26 08:01

Lothre1


1 Answers

Solution 1

Add class="icon-large" to your ion-icon.

Solution 2

The easiest would have been indeed to use style:"font-size:2em;" property in the ion-icon element, however rightly noted that Ionic (actually Angular) removes HTML from elements. The workaround would be to use a pipe. It is quite involved (e.g. see https://medium.com/@ahmedhamedTN/make-styles-work-when-dealing-with-innerhtml-in-angular-ac2d524ba001).

Non-Solution

We can get SCSS to style the message itself inside ion-toast, by using the following:

ion-toast::part(message) {
 ...
}

However its impossible to style ion-icon inside the message (see note below).

Solution 3

We can still get SCSS file to change the ion-icon size... Add a button with an icon and then style it:

page.ts:

const opts = {
  ...
  buttons: [
    {
      side: 'start',
      icon: 'icon-name',
      handler: () => {},
    },
  ],
};
const toast = await this.toastController.create(opts);
toast.present();

page.scss:

ion-toast::part(button) {
  height: auto;
  width: auto;
  font-size: 1.6em; // this sets actual icon size
}

Why:

Since parts of the toast are placed inside #shadow-root, the only way to get to them from SCSS is by using "::part()" as assigned by components themselves. To find which parts are available, read the docs: https://ionicframework.com/docs/api/toast#css-shadow-parts, or open inspector, find .ion-toast and review elements inside under #shadow-root. For Ionic 5 Angular I found part=(container), part=(message) and part=(button).

Note that part() cannot be followed by any other selectors. So it makes it impossible to make icon on the left larger but keep close button same size, as they both have "part=(button)".

like image 82
iva2k Avatar answered Feb 02 '26 20:02

iva2k