Utilize .NET MAUI Blazor's customizable light and dark themes by loading unique stylesheets through the headcontent feature

I am currently working on a .net MAUI Blazor Hybrid app and I am looking to create both a dark and light theme using CSS stylesheets, without relying on MudBlazor.

My approach involves using two separate CSS files, lightMode.css and darkMode.css, each containing the appropriate color schemes for their respective themes. The goal is to have the MainLayout, and subsequently all pages, switch to using the darkMode.css when dark mode is activated.

For example, within MainLayout.razor:


<HeadContent>
    @if (isDark)
    {
        <link href="css/darkMode.css" rel="stylesheet"/>
    }
    else
    {
        <link href="css/lightMode.css" rel="stylesheet"/>
    }   
</HeadContent>

// HTML and C# code here

However, I am facing an issue where the HeadContent is not being placed within the head tag of the page. Even when directly added to the index.html page, only the last stylesheet mentioned seems to take effect.

I have searched for alternative solutions, but most do not mention how to achieve this using CSS, unlike the approach I am trying to implement. References like the following post have not provided the specific guidance I need: Light and dark theme for my Maui Blazor app

Any advice on how I can successfully implement a dark/light theme switch using CSS? I am open to other ideas as well, though this method seems the most straightforward to me.

Thank you in advance for your help.

Answer №1

My approach ended up being slightly different since I faced issues with HeadContent not functioning properly after removing the Bootstrap components to customize the styling completely.

Instead, I decided to follow a revised version of another solution provided by @benjamin on Stack Overflow: . I opted not to manipulate the HTML elements by adding or removing classes.

My method involved directly accessing the <head> element and the stylesheet <link> containing the theme CSS file using HTML and JavaScript manipulators to switch between light and dark themes based on the toggle.

Allow me to elaborate further on the implementation:

Here's a snippet of my code: In the MainLayour.razor class, I included this simple line to handle the theme switching:

<ElementManipulator IsDarkTheme="_isDark"></ElementManipulator>

The _isDark variable is determined by a basic toggle button.

The functionality is contained within the ElementManipulator.razor class:

@inject IJSRuntime JSRuntime

@code {

    protected override async Task OnParametersSetAsync()
    {
        if (IsDarkTheme is not null)
            await JSRuntime.InvokeVoidAsync("toggleThemeStyleSheet", IsDarkTheme);
    }

    [Parameter]
    public bool? IsDarkTheme { get; set; }
}

This code triggers the toggleThemeStyleSheet function in the JavaScript file ElementManipulator.js:

var getHeadElement = function () {
    return document.getElementsByTagName("head")[0];
};

var toggleThemeStyleSheet = function (isDarkTheme) {
    let themeLink = getHeadElement().getElementsByClassName("theme")[0];
    let theme = isDarkTheme ? "darkTheme.css" : "lightTheme.css";
    themeLink.href = "_content/MyProject.UI/css/" + theme;
};

This setup facilitates the seamless swap between the lightTheme.css and darkTheme.css stylesheets.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery width property does not seem to be functional on menus that do not contain any dropdown

I am currently working on creating a menu that displays arrows underneath the items when hovered over or when the .active class is added to the menu. Everything is working fine, except for the fact that it only works on menus with drop-downs and the child ...

Switch picture when hovering over button image

Looking for a solution where I have 2 images - one inactive and the other active. I want the inactive part of the image to change to active when someone hovers over it. Here are the pictures: I was able to achieve this using mapster, but it's not res ...

Exploring the growth of CSS offsetting alongside with AngularJS

I am working on an Angular app where I need to increase the left offset of a div by 90px every time the slideThis() function is called. In jQuery, I would typically achieve this using left: '+=90', but I'm struggling to find a similar method ...

Implementing a Radial Cursor with a Custom Background Image in JavaScript

I am attempting to implement a radial cursor on a website that features a background image. Currently, I am facing two main issues: The radial cursor works in Chrome but not in Firefox. When using Firefox, I encounter a parsing error related to the "bac ...

Enhance the aesthetics of placeholder text in Semantic UI React using CSS styling

Currently, I am utilizing Semantic UI dropdowns within my React application to generate drop-down menus similar to the ones showcased in their documentation found here: The initial text displayed is "Select Friend", and it appears with a semi-transparent ...

Designing a Dynamic Floating Element that Shifts with Scroll Movement

Hey there everyone!, I am currently working on a project in Wordpress and I was wondering if anyone has experience creating a floating widget that moves along with the page as you scroll. Any suggestions on how to achieve this? Would it involve using Javas ...

Position the two input boxes next to each other

I need help re-arranging my input boxes on a web page. Currently, they are stacked on top of each other vertically and I would like them to be displayed horizontally with two boxes per row. Here is an example of how I'd like them to look: https://i.ss ...

Bootstrap 4's Img-fluid class fails to properly resize images

Having a bit of trouble with my navbar setup. I want to use an image brand with img-fluid so it resizes to fit the div and remains responsive. However, instead of resizing, the image just stretches out the navbar making it huge. Here's my code: ...

Adjust the size of the input field as text is being typed in

Can a text input box be automatically resized as text is entered? I've been looking online but haven't come across any solutions. ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

Adjusting Screen Size for Lottie Animation in React.js

I need assistance with resizing a lottie animation component on my website's landing page to set its display to none on mobile devices. How can I achieve this? See the lottie component code below: import React from "react"; import Lottie fr ...

Data displayed in a table-like format

Is there a way to achieve this layout view image here (currently done using tables) while maintaining semantic markup? I believe the best tag for this would be dl. Each cell should have the height of its corresponding row. EDIT: The left column contains d ...

The code functions perfectly on JSfiddle, but for some reason it halts when implemented on

Unfortunately, the code that was working perfectly on JSfiddle seems to be encountering issues when implemented on a regular HTML site. The content loads fine but there seems to be an error with the preview function after selecting an image. We have colla ...

Tips for handling the !important declaration when creating a customized bootstrap theme

Exploring the Color Dilemma After creating a simple website in Bootstrap 4.1 with a distinct shade of purple, I encountered an issue with specificity when it came to customizing button states. To address this, I introduced a CSS class called .btn-purple ...

Lines that are next to each other within an svg path and have a stroke

I'm working with an SVG that contains multiple lines within a path element. <path stroke-width="13" stroke="black" fill="orange" d="M 100 100 L 300 100 Z L200 300 z"/> Due to the stroke-width, the lines a ...

Ensure that the width of the inner table matches the width of its contents within an overflowing div

I'm facing an issue with a table inside a div styled as table-wrapper: .table-wrapper { display: inline-block; overflow-x: scroll; width: 800px; } Although I want the div to display a horizontal scrollbar so that the table inside it can ...

What causes the empty gap between the accordion title and its content in Bootstrap?

I'm currently working on a Bootstrap accordion and I've encountered a problem where a white line appears underneath the heading whenever I click to expand it. Here's the accordion Here's my current code snippet: HTML - All divs do clo ...

Keep moving the box back and forth by pressing the left and right buttons continuously

Looking to continuously move the .popup class left and right by clicking buttons for left and right movement. Here is the js fiddle link for reference. This is the HTML code structure: <button class="right">Right</button> <button class="l ...

How can I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

Can a button be connected to both navigate to another webpage and trigger a modal to appear on it simultaneously?

Is there a way to connect a button to a modal on a different page so that when the button is clicked, it opens another page (in a new tab with target 0) with the modal already displayed? ...