

Discover more from Mark’s Wiki
I was making background image changer for my eLearning project using Blazor and ran into a fun trick I’d like to share. If you want to change a background image, you can do this by applying a CSS class to an HTML tag. One common approach in Blazor would be to store this class name in a variable, and then swap the contents of the variable at runtime.
This sort of class-swap is normal with Blazor, but for a webbier flavor, we could use CSS variables (aka custom properties). Consider the following style that sets the background-image using a CSS variable.
<div class="my-background">
<style type="text/css">
:root {
--background-image: url(@image);
}
.my-background {
background-image: var(--background-image);
}
</style>
@code {
string image=String.Empty;
}
Now we have established a link between a C# variable “@image”, and a CSS variable “-background-image”. If you make a change to the C# variable, Blazor will detect this and change the value in the style tag, thus changing the css-variable. When the CSS variable changes, the browser will detect this and update the background image. Let’s add some code:
void Swap()
{
if(swap){
swap = false;
image = "background-example-1.png";
}
else{
swap = true;
image = "background-example-2.png";
}
}
I was surprised and delighted that this worked great without any JavaScript or the need for JSInterop(). I know it’s a bit unconventional, but I really like the low-code approach here. I have not tested this approach for performance, but I’ll bet you a beer that CSS variables are just as fast to render changes than Blazor. I’m calling this “CSSInterop” and I’m going to see if it makes sense in other scenarios as well.
Link to working demo: https://blazorfiddle.com/s/wkevjmfl
Please take CSSInterop for a spin and let me know how it works for you on Threads where you can find me as “marks.wiki”