user1675891
user1675891

Reputation:

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?

Upvotes: 0

Views: 782

Answers (2)

Serge In&#225;cio
Serge In&#225;cio

Reputation: 1382

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

Upvotes: 3

Fred Truter
Fred Truter

Reputation: 666

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.

Upvotes: 2

Related Questions