Hey folks! After struggling with clean theme switching in multiple Blazor projects, I built a library to solve it once and for all. It’s called BlazorThemes and it’s now at v1.0.1!
Key Features:
- Auto dark/light mode that follows OS preferences
- Time-based scheduling for automatic theme switching
- Custom themes with CSS variables
- Cross-tab synchronization
- Zero flash on load
How To Use:
install the package:
dotnet add package BlazorThemes
register the service in the Program.cs file:
builder.Services.AddBlazorThemes(options => {
options.Themes = new[] { "light", "dark", "auto" };
options.EnableSystem = true;
options.TransitionType = "fade";
});
or simply for default use case:
builder.Services.AddBlazorThemes();
Add Theme Provider:
<BlazorThemesProvider>
<Router AppAssembly="@typeof(App).Assembly">
<!-- Your app content -->
</Router>
</BlazorThemesProvider>
set the theme easily :
<div class="theme-controls">
<button @onclick='() => ThemesService.SetThemeAsync("light")'
class="btn btn-light">
☀️ Light
</button>
<button @onclick='() => ThemesService.SetThemeAsync("dark")'
class="btn btn-dark">
🌙 Dark
</button>
<button @onclick='() => ThemesService.SetThemeAsync("auto")'
class="btn btn-auto">
🔄 Auto
</button>
</div>
and you can style your component like this way :
/* Theme-specific variables */
[data-theme="light"] {
--bg-primary: #ffffff;
--bg-secondary: #f8fafc;
--text-primary: #1e293b;
--accent-primary: #3b82f6;
/* ...other variables */
}
[data-theme="dark"] {
--bg-primary: #0f172a;
--bg-secondary: #1e293b;
--text-primary: #f1f5f9;
--accent-primary: #60a5fa;
/* ...other variables */
}
/* Component styling using variables */
.component {
background-color: var(--bg-primary);
color: var(--text-primary);
border: 1px solid var(--border-primary);
}
.button {
background-color: var(--accent-primary);
color: var(--text-on-accent);
}
Check it out for more features:
GitHub: BlazorThemes
NuGet: BlazorThemes Package
This is Version 1.0.1, and I’d love it if you gave it a spin. Bug reports, feature ideas, or any suggestions are more than welcome. I'm open to feedback, collaborations, or anything that helps improve it!
Top comments (0)