Search code examples
angularionic-frameworkionic5

How to add custom theme to Ionic 5 application?


I need to add custom theme to Ionic 5 app. I was trying to add red-theme to variables.scss

@media (prefers-color-scheme: red) {
  :root {
    --ion-color-primary: red;

And then I am trying to initialize it through index.html

 <meta name="color-scheme" content="red" />

But it's not working. I also tried to add toggle javascript code from https://ionicframework.com/docs/theming/advanced

Is it possible to theme your Ionic application by adding new primary, secondary and tertiary colors and then changing them at run time?


Solution

  • You can only use the prefers-color-scheme media query for dark and light themes.

    To add a new custom theme to Ionic, you simply create a new CSS class for it and overwrite every color variable under this CSS rule:

    variables.scss

    body.red {
      --ion-color-primary: red;
      /*...*/
    }
    

    You can generate the rest of the colors with the Color generator and the Stepped color generator. Finally you might want to tweak some specific color variables such as --ion-toolbar-background etc., for ios and md modes, you can look at the Default dark colors, copy and edit the rest of the colors from there.

    After that, you can create a button which toggles the .red class on the body element and also store the preferred theme inside localStorage or use a cookie and toggle the class when your app loads:

    main.ts

    const theme = localStorage.getItem('theme')
    
    document.body.classList.toggle('red', theme === 'red')