Add Dark mode in Ionic Framework, Tailwind CSS in just 2 min

Add Dark mode in Ionic Framework, Tailwind CSS in just 2 min

To add a dark mode feature to an Ionic app using Tailwind CSS, you can follow these steps:

  1. In your Ionic project, install the ionic-CSS-utils package by running the following command:
npm install ionic-css-utils
  1. In your Tailwind CSS configuration file (typically named tailwind.config.js), add the following lines to define two color modes: light and dark:
module.exports = {
  theme: {
    extend: {
      colors: {
        'dark-mode': '#1e1e1e',
      },
    },
    extend: {
      backgroundColor: {
        'dark-mode': '#1e1e1e',
      },
    },
  },
  variants: {},
  plugins: [],
  corePlugins: {
    container: false,
  },
  dark: 'class',
  light: {
    backgroundColor: 'white',
    color: '#1e1e1e',
  },
}
  1. In your main Sass file (typically named variables.scss), define a variable for the light and dark mode colors:
$dark-mode: #1e1e1e;
$light-mode: #ffffff;
  1. Add a toggle button in your main HTML file to switch between the light and dark modes. You can do this by adding the following code:
<ion-button (click)="toggleDarkMode()">Toggle Dark Mode</ion-button>
  1. In your component's TypeScript file, define the toggleDarkMode function to toggle the dark class on the html element:
toggleDarkMode() {
  document.querySelector('html').classList.toggle('dark');
}
  1. In your main Sass file, add the following lines to apply the dark mode colors when the dark class is present on the html element:
html.dark {
  --ion-color-primary: $dark-mode;
  --ion-color-secondary: $dark-mode;
  --ion-color-tertiary: $dark-mode;
  --ion-color-success: $dark-mode;
  --ion-color-warning: $dark-mode;
  --ion-color-danger: $dark-mode;
  --ion-color-light: $dark-mode;
  --ion-color-medium: $dark-mode;
  --ion-color-dark: $dark-mode;

  --ion-background-color: $dark-mode;
  --ion-text-color: $light-mode;
  --ion-toolbar-background-color: $dark-mode;
  --ion-toolbar-color: $light-mode;
}

That's it! When you click the toggle button, the app will switch between the light and dark modes.