Blazor WASM Dark Theme and Light Theme
In this article, let's learn about how to configure dark theme in Blazor WASM application.
Table of Contents
What is Dark Theme and Why it is needed?
Dark Mode or Theme has become common nowadays. Almost all the operating system, apps and websites started supporting Dark Mode as first class feature as it gives a pleasing experience to eyes when reading or using the app at night time. So it's time to design dark version of apps or website to go along with the default design. Let's see how we can implement this in Blazor application.
Steps to configure dark theme
First, lets have a
DisplayMode to represent different display modes. Next, we need the help of
Dark mode or
System mode to let it detect
based on operating systems default display mode.
Code Sample - Display Theme Component to toggle Display Mode
When we click on button to set theme or mode,
SetTheme(DisplayMode displayMode) method is called by
which in turn will use
onDisplayModeChanged function. If the selected
System and if the operation system has dark
theme enabled? then we can set
dark CSS Class to
HTML document and store the user preference in
Local Storage to retain it for next time when the user visits our app.
If the user has selecetd
DisplayMode then we can remove the
dark CSS Class from the
HTML document and also remove the entry from
Now that all set, we need to make sure to load the user preference when the user visits our site anytime in future. For this we can again use small
index.html to check if the
Local Storage entry has
DisplayMode key with
dark value or we can
check if the operating system supports
Dark mode. In both case we can add
dark CSS class back to
HTML document. If both the above cases are not met then, we can leave it to default light theme.
Time for a live demo. Try with below demo and make sure to inspect and see how CSS classed are toggled in
HTML along with
Local Storage changes.
Demo - Display Mode
Click on one of the display mode and see how the I ❤️ DotNet responds.
In this article we saw how to configure dark theme in blazor wasm application. We saw how to apply system theme by default and we also saw a live demo of how i love dotnet responds to dark theme.