Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set CSS Variable 'deeply' for Theming in Blazor [closed]

mylayout.razor.css

:root {
  --clr-one: blue;
  --clr-two: red;
}
.wrapper.normal {
  --bg: var(--clr-one);
  --clr: var(--clr-two);
}
.wrapper.reversed {
  --bg: var(--clr-two);
  --clr: var(--clr-one);
}
.title {
  background-color: var(--bg);
  color: var(--clr);
}

mylayout.razor

<div class="wrapper @Theme">
    <div class="title">
        My Title
    </div>
    @Body
</div>
@code {
  string Theme = mycondition ? "normal" : "reversed";
}

Using the above, the colors of my "title" will switch depending on the value of "mycondition". I feel like I'm on the way the being able to theme from the layout.

I can now change the :root colors and that will affect the 'themes' so I can play with those base colors until I'm happy.

Given that "title" is a child of "wrapper", I had assumed that the variables --bg and --clr assigned on the "wrapper" would propagate to all child elements. But ...

myroutable.razor.css

.header {
   background-color: var(--bg);
}

myroutable.razor

@page "/myroutable"
@layout mylayout
<div class="header">
    My Header
</div>

The problem is that the "header" is not getting the value of the --bg variable from the layout.

Hopefully the above explains what I'm after. Any ideas how I might achieve this?

UPDATE

It turns out the problem was a stoopid typo in the child razor component! I'll leave the question here though as the pattern above is one viable way of delivering theming in a razor app.

like image 676
Neil W Avatar asked May 17 '26 02:05

Neil W


1 Answers

The pattern outlined in the question is fine.

The problem was a typo in using the variable name in a sub-component, so using the pattern in the question will work for dealing with theming within a particular layout.

like image 194
Neil W Avatar answered May 18 '26 16:05

Neil W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!