asp.netasp.net-core-mvctag-helpers

CSS not applied to img in ASP.NET


I'm creating an ASP.NET MVC project and I'm trying to apply some css to an image.

Project structure

And this is the code:

//Index.cshtml.css
h1 {
    color: green
}

.roundImage {
    border-radius: 50px;
}

#profilePhoto {
    width: 200px;
    margin: 2rem 0;
    border-radius: 50%;
}
//Index.cshtml
<div class="text-center">
    <h1 class="display-4">My name</h1>
    <img class='roundImage' id="profilePhoto" src="~/images/me.jpg" alt="Profile photo" />
</div>

The color of the h1 is being applied but I have tryed both approaches for the img and it did not work. Why is that and how could I fix it?


Solution

  • Firstly, <img> is a built-in Tag Helper. We can also notice the differences between tag helper and normal html element in VS.

    enter image description here

    Then due to tag helper occurred at runtime while css isolation occurred at build time, css isolation classes are not able to apply to tag helper. Just like we can see, img tag isn't applied the unique identifier, while the div and h1 tags are having it.

    enter image description here

    So the solutions are preventing <img> tag to be recognized as tag helper, or put the class for <img> out of css isolation. Per my test, using opt-out character "!" like <!img> doesn't work for our scenario. Just like the screenshot below, the identifier of CSS isolation will break the html tag. So that I still recommend to put the class definition out of css isolation file.

    enter image description here