Light Mode and Dark Mode
Many of today’s websites provide the option to view a website in either a light mode or a dark mode. While other websites honor the
system default to decide to use light mode or dark mode. Personally, I think a
website should just use the system default. I can understand that a user might
want to view your website in dark mode, or maybe they just want to
view it in a different mode just once.
If you prefer system default or allow the user to set the
mode, it is a nice feature to allow the
user to switch to either dark or light mode. With Tailwind, this is a
straightforward process.
How it
works
To implement the light-dark mode switch feature, a user
simply clicks on a switch that selects which mode they want:
Implementation
There are five steps that must be implemented in other to support this feature.
1. In the TailwindCss configuration set the dark Mode under the Export modules to class. If this is not defined Tailwinds will use the system defaults.
darkMode: 'class',
content: ['./**/*.{razor, html, cshtml}'],
theme: {
extend: {},
},
plugins: [],
}
a. On your elements use the dark: prefix to apply the styles you have in dark mode.
3. Create the UI switch
a. This can be any UI, from a simple check box, a button, or a nice check box like the above.
4. Add an event handler to the UI switch
@onclick=ToggleDarkMode
5. Change the class at the main container element.
a. For Blazor this would be in the main layout, the main div
<div class="flex flex-col sm:flex-row w-screen h-screen relative @darkMode">
This is normally called class toggling and is one of the coolest things you can do in C# and Blazor. The actual method is defined as:
private void ToggleDarkMode()
{
if (string.IsNullOrEmpty(darkMode))
{
darkMode = "dark";
}
else
{
darkMode = "";
}
StateHasChanged();
}
We are setting the value to “dark” if it is empty else we set the value to an empty string.
In the source code listed at the bottom, I made a simple change between light and dark modes so you could see the difference when switching between the two modes. Again, you have total freedom to style your application to meet your needs.
Summary
This project turned out to be easier than I had anticipated. I can thank TailwindCss for that. I continue to be impressed with the ease of the things you can do with TailwindCss. I plan to continue to explore all the features of Tailwinds.
Comments
Post a Comment