I’m creating an ASP.NET MVC project and I’m trying to apply some css to an image.
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?
2
Answers
The cshtml.css will add a scope-identifier:
You can open developer mode in the browser and see the h1 tag is working with the color green.
BUT you will see the CSS styles are with an id [b-34vq99bu2v]
That is the reason the CSS is not working for the image.
You can add the scope id inside img like:
Then that will work.
Reference: Razor Pages – CSS Isolation – styles for some HTML tags are not working
Firstly,
<img>
is a built-in Tag Helper. We can also notice the differences between tag helper and normal html element in VS.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.
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.