To add a dark mode feature to an Ionic app using Tailwind CSS, you can follow these steps:
- In your Ionic project, install the ionic-CSS-utils package by running the following command:
npm install ionic-css-utils
- 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',
},
}
- 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;
- 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>
- In your component's TypeScript file, define the
toggleDarkMode
function to toggle thedark
class on thehtml
element:
toggleDarkMode() {
document.querySelector('html').classList.toggle('dark');
}
- In your main Sass file, add the following lines to apply the dark mode colors when the
dark
class is present on thehtml
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.