Home > Enterprise >  Warnings about dynamic inline CSS in Blazor
Warnings about dynamic inline CSS in Blazor

Time:12-25

Not sure if this should be fixed in Blazor or Visual Studio, but I have a Razor page with an inline CSS section that contains styles generated based on some logic, so it has to be dynamic and inline. This makes Visual Studio show a warning CSS039 about Unexpected character sequence in property value.

@{ var styles = new List<string>(); }

<div ></div>

<style type="text/css">
  .some-element {
    background-image: @(string.Join(",", styles)); /* Warning is here */
  }
</style>

enter image description here

Questions

  1. Blazor: is it possible to have dynamic CSS in a separate file?
  2. Visual Studio: trying to suppress this warning in .editorconfig file, why it's not going away?
root = true

[*]
indent_style = space

[*.cs]
dotnet_diagnostic.CSS039.severity = none

[*.razor]
dotnet_diagnostic.CSS039.severity = none

[*.css]
dotnet_diagnostic.CSS039.severity = none

CodePudding user response:

This seems to get rid of the warning.

<style type="text/css">
    .some-element {
        background-image: @string.Join(",", styles);
    }
</style>

If for some reason you had a more complicated code block that required the @() you could also just compute the string as a local variable in the above code block and then reference it directly in you style.

E.g.

@{
    var styles = new List<string>() {"MyBackground.png"};
    var backgroundImage = string.Join(",", styles);
 }

 <div ></div>

 <style type="text/css">
     .some-element {
         background-image: @backgroundImage;
     }
 </style>

CodePudding user response:

I don't recommend doing it this way. The reason to define styles with class names is for readability, reusability and so on-- things that don't apply if you're dynamically generating style attributes.

Therefore, it's fine to just use inline style attributes wherever you'd have used your class:

<div style="@styleattributes" />

@code {
    string styleattributes = "background-color: black; width:50%;";
}
  • Related