Paul Michaels
Paul Michaels

Reputation: 16705

Trouble getting a background image to appear in HTML

I have the following HTML code:

<div style="background-image:url(~/Images/MyImage.jpg); width:100%; height:100%">

I'm not too familiar with HTML, but form all the articles I've seen, this should work fine. If I show the image in an asp.net image control then it shows fine. However, I want to put text on top of it. Can anyone tell me what I'm doing wrong, please?

Upvotes: 1

Views: 241

Answers (3)

Daniel Vassallo
Daniel Vassallo

Reputation: 344431

By default, you cannot use the ~ in the paths of normal HTML elements. That would only be understood by ASP.NET, but your element is being treated as markup and simply sent to the browser without being processed by the server-side script.

You should either add an id attribute and the attribute runat="server" to your <div> so that it is recognized by ASP.NET, or else you would have to use a relative or absolute URL without the ~ in the path:

<div id="mydiv" style="background-image:url(~/Images/MyImage.jpg);" runat="server">

or

<div style="background-image:url(/Images/MyImage.jpg);">

Upvotes: 2

loxxy
loxxy

Reputation: 13151

In the case above whatever text you put between the <div ...> </div> would come over the background image.

Also as the runat = server tag is missing it won't even be touched by asp.net. So your url is also wrong by using ~.

Upvotes: 1

mamoo
mamoo

Reputation: 8166

Your div is not evaluated as a server control, thus the "~" char is not recognized as it should. Not 100% sure, but adding runat="server" should work...

<div style="background-image:url(~/Images/MyImage.jpg); width:100%; height:100%" runat="server">

Upvotes: 1

Related Questions