Michael
Michael

Reputation: 1010

Blazor Webassembly: CSS :host variables not applied

I am working on a layout for a Blazor Webassembly component. (=Fat browser client, no server rendering)

The layout looks like this and works as expected:

.grid 
{
    min-height: 100vh;
    min-width: 100vw;
    height: 100vh;
    width: 100vw;
    background-color: black;
    display: grid;
    grid-template-rows: 10px 5vh calc(90vh - 20px) 5vh 10px;
    grid-template-columns: 10px 3vw calc(94vw - 20px) 3vw 10px;
    /*Blazor Special*/
    margin: -8px;
}
.gridCellLogo 
{
    grid-column-start: 2;
    grid-column-end: 2;
    grid-row-start: 2;
    grid-row-end: 2;
    background-color: red;
}
<div class="grid">
    <div class="gridCellLogo">
        @*Put your component here*@
    </div>
</div>

However, if I use CSS variables, they are not applied. Look at --somecolor

:host
{
    --somecolor: green;
}

.grid {
    min-height: 100vh;
    min-width: 100vw;
    height: 100vh;
    width: 100vw;
    background-color: var(--somecolor);
    display: grid;
    grid-template-rows: 10px 5vh calc(90vh - 20px) 5vh 10px;
    grid-template-columns: 10px 3vw calc(94vw - 20px) 3vw 10px;
    /*Blazor Special*/
    margin: -8px;
}

My question:

Is my CSS wrong or is Blazor Webassembly not ready for CSS variables yet?

Upvotes: 1

Views: 1783

Answers (2)

Angel Munoz
Angel Munoz

Reputation: 21

Blazor css Isolation doesn't use shadow DOM so the :host selector is not available. You can define your variables on the :root selector and then override it with your custom value on a particular css class like this

<div class="grid my-warpper-class">
    <div class="gridCellLogo">
        @*Put your component here*@
    </div>
</div>
:root
{
  --somecolor: red;
}

.my-wrapper-class
{
  --somecolor: green;
  /* blue here is a fallback in case --somecolor didn't exist */
  background-color: var(--somecolor, blue);
}

.gridCellLogo {
  background-color: var(--somecolor, green);
}

defining the --somecolor variable on the :root will make it available everywhere, when you can overwrite it in any other class like my-wrapper-class

in that case the wrapper class and the gridCellLogo will have different background colors

Upvotes: 2

Cory Podojil
Cory Podojil

Reputation: 854

Are you using Blazor CSS Isolation? E.g., MyComponent.razor.css? If so, CSS Isolation does not support pseudo classes, variables, or any CSS that starts with a single colon :.

You will need to declare these variables in a non-compiled CSS file like the app.css under wwwroot/css.

Upvotes: 8

Related Questions