cssblazor-webassembly

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


Does CSS variables work in a Blazor component with CSS islolation 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?


Solution

  • 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);
    }