Search code examples
htmlcssasp.net-mvcimageurl-action

Can't style an anchor <a> with an image


According to this answer, I'm supposed to be able to style my anchor tag as follows.

<a href="@Url.Action("Index", "Home")" 
   style="background: no-repeat url(../../Images/Logo.png) 0 0"></a>

However, I noticed that it doesn't work as expected because the image doesn't appear on the screen. However, if I create an image tag inside, it does.

<a href="@Url.Action("Index", "Home")">
  <img src="../../Images/Logo.png" />
</a>

I'd prefer using the second approach but I'm afraid that it's old-school and that today it's recommended to use styling for adding images and not mark-up. So, naturally I want to embrace the new ways.

What am I doing wrong?


Solution

  • Ensure your <a> tag is styled to be large enough to display the image. By default this tag is displayed inline and you have given no content between the <a> and </a> tags, so therefore the browser will allocate no screen space at all for this element.

    I suggest adding some rules to your inline style attribute (well it is better still in a stylesheet to be honest):-

    <a href="@Url.Action("Index", "Home")" style="
       background: no-repeat url(../../Images/Logo.png) 0 0; 
       display: inline-block; 
       width: 30px; 
       height: 20px"></a>
    

    Just replace the 30px and 20px with the actual dimensions of your image.