Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Blazor Web Assembly work with CSS variables in CSS Isolation files?

Does CSS variables work in a Blazor component with CSS isolation files ?
When my component named Test.razor has no CSS isolation file and has the style set:

<h1 class="mh1">Test</h1>
<style>
    :root {
        --mblue:#0000ff;
    }

    .mh1{
        color:var(--mblue);
    }
</style>

Test is indeed blue.
However if I put the styles in a isolation file name Test.razor.css it does not work.

:root {
    --mblue: #0000ff;
}

.mh1 {
    color: var(--mblue);
}

The component Test resides in the index page:

@page "/"
<Test></Test>

What am I doing wrong?

like image 602
Paul Stanley Avatar asked Jun 14 '26 03:06

Paul Stanley


2 Answers

The answer is yes, but not so sure that you can use :root in a css isolation file (the class is no longer called :root in a css isolation file -- it gets a random suffix with css isolation).

My approach has been as follows:

  1. Use a wrapper element to provide a context to assign the css variables to.
  2. Then use the variable in the class you assign to the relevant element.

Test.razor

<div class="test-wrapper">
    <h1 class="mh1">Text</h1>
</div>

Test.razor.css

.test-wrapper {
    --mblue: #0000ff;
}

.mh1 {
    color: var(--mblue);
}
like image 108
Neil W Avatar answered Jun 15 '26 22:06

Neil W


What I think you're looking for is ::deep.

I found it on https://learn.microsoft.com/en-us/aspnet/core/blazor/components/css-isolation?view=aspnetcore-9.0

::deep {
    --mblue: #0000ff;
}
like image 20
MrSethT Avatar answered Jun 15 '26 21:06

MrSethT