0

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?

Community
  • 1
  • 1

2 Answers2

3

You need to set the style to display: block; and give it a width and a height.

Example:

<a href="@Url.Action('Index', 'Home')" style="background: no-repeat url(https://wiki.mageia.org/mw-en/images/thumb/c/c8/Chromium-64px-logo.png/35px-Chromium-64px-logo.png) 0 0; display: block; width: 50px; height: 50px;"></a>

Hope this helps

Serge Inácio
  • 1,366
  • 9
  • 22
  • 1
    Wouldn't it be even wiser to set it to `inline-block` as @Fred suggests? It's going to be used **inline** so the way I figure, we only need to "blockify" it a little bit. Or am I confusing the concepts? –  Jan 02 '16 at 12:56
  • Depending on what you want to achieve, if it is going to be used **inline** then @Freds suggestion is wiser. – Serge Inácio Jan 02 '16 at 12:59
  • Thank. In any case +1 for the snippet. –  Jan 02 '16 at 13:00
2

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.

Fred Truter
  • 667
  • 4
  • 10
  • Oh, I see. Would you say it's a more modern approach to use the styling-in-images? –  Jan 02 '16 at 12:54
  • Yes, I agree styling buttons/links using images is more modern, but take care not to burden your site with too many graphics as it slows down the initial page loading and rendering (on slower devices). Take a look at [CSS sprites](http://webdesign.tutsplus.com/articles/css-sprite-sheets-best-practices-tools-and-helpful-applications--webdesign-8340) to save on loading times. – Fred Truter Jan 03 '16 at 00:48