John Davidson

javascript - Tailwind CSS - Switch color theme between "light", "dark" or "system settings"

0 comments
Message:


Tailwind CSS provides two different ways to enable dark mode on your website.


The first way is through media, which means if your OS supports dark mode and it's activated. Your website will be automatically displayed in dark mode.


My tailwind.config.js:


module.exports = {
darkMode: 'media',
};

The second way is through "class", meaning if your <html> tag has the class="dark" assigned. Your website will be displayed in dark mode.


My tailwind.config.js:


module.exports = {
darkMode: 'class',
};

Is there a simple way of using both of these options at once?


The effect I want to achieve is that the user can set their preference between "light", "dark" and "system settings".


Similar to the function that is used here on Stack Overflow:



If this option is not currently possible with Tailwind CSS, what would be the cleanest and simplest workaround?


Information about my project:



  • Tailwind CSS

  • Laravel 8

  • Fortify

  • Jetstream

  • Livewire



My Answer:
To switch color themes between light and dark mode in Tailwind CSS using JavaScript, you can add a class to the `body` element to toggle between the two themes. Here's an example of how you can achieve this:

1. Define your light and dark mode color classes in your Tailwind CSS configuration:

javascript
// tailwind.config.js

module.exports = {
theme: {
extend: {
colors: {
light: {
primary: '#ffffff',
secondary: '#f3f4f6',
// Add more light mode colors here
},
dark: {
primary: '#1a202c',
secondary: '#2d3748',
// Add more dark mode colors here
},
},
},
},
}


2. Create a function in your JavaScript file to toggle between light and dark mode:

javascript
function toggleColorTheme() {
const body = document.querySelector('body');
body.classList.toggle('dark');
}


3. Add a button or any other element to trigger the color theme switch:

html



4. When the button is clicked, the `toggleColorTheme` function will add or remove the `dark` class from the `body` element, switching between the light and dark mode color themes.

You can customize the color classes and styles in your Tailwind CSS configuration to fit your design preferences.

Rate this post

4 of 5 based on 8704 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us