Search code examples
cssasp.net-coreblazor.net-7.0asp.net-core-css-isolation

changing the style of InputText using css isolation


I am new to blazor and I am trying to change the style of InputText using css isolation.

The style can be changed if I set it inline or internally, but it does not work when I try to set it using css isolation. I've looked at the docs and it is stated that

Scoped CSS only applies to HTML elements and not to Razor components or Tag Helpers, including elements with a Tag Helper applied, such as < input asp-for="..."> /.

Is InputText a Razor component and is this why I cannot change the style using css isolation? Would love to get any advice on this!


Solution

  • First of all, InputText is certainly to be a razor component, it's one of the built-in input components. So that css isolation doesn't work in InputText should be the expected behavior. In the meantime, we have below explanation in the document to explain why we use inline style in InputText could successfully change the style.

    All of the input components, including EditForm, support arbitrary attributes. Any attribute that doesn't match a component parameter is added to the rendered HTML element.

    As a workaround, we might put the class definition into wwwroot->css->site.css, or <style> .input-text-r { color: blue; } </style> in the razor component or using inline style if it doesn't against your CSP policy. Or append the class dynamically after the page has rendered if required in some specific scenarios, using codes like below.

    <InputText class=@classvalue @bind-Value="starship.Identifier" />
    
    protected override async Task OnInitializedAsync()
    {
        classvalue = "input-text-r";
    }