skip to Main Content

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?

2

Answers


  1. 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.
    enter image description here

    BUT you will see the CSS styles are with an id [b-34vq99bu2v]
    enter image description here

    That is the reason the CSS is not working for the image.

    You can add the scope id inside img like:

    <div class="text-center">
        <h1 class="display-4">My name</h1>
        <img b-34vq99bu2v class='roundImage' id="profilePhoto" src="~/images/ILTW.png" alt="Profile photo" />
    </div>
    

    Then that will work.
    enter image description here

    Reference: Razor Pages – CSS Isolation – styles for some HTML tags are not working

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search