8

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?

2 Answers 2

13

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Having come from c# - Just getting to grips with CSS etc. I thought :root had some special significance. Thanks Neil.
You can also add your variables in the app.css (or other global css file that's declared in your index.html) and use them in your razor css files. You won't get the intellisense, but it'll work.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.