Assume I have an \"images\" folder directory under the root of my application. How can I, from within a .css file, reference an image in this directory using an ASP.NET app
On Windows 7, IIS 7.5:
Not only do you have to do the steps mentionned by Marcel Popescu.
You also need to add a handler mapping in IIS 7.5 handler mappings. So that IIS knows that *.css must be used with the System.Web.UI.PageHandlerFactory
It's not enough to just set the stuff in the web.config file.
Marcel Popescu's solution is using Request.ApplicationPath in the css file.
Never use Request.ApplicationPath - it is evil! Returns different results depending on the path!
Use the following instead.
background-image: url(<%= Page.ResolveUrl("~/images/bg_content.gif") %>);
Put your dynamic CSS in a user control in an .ascx file and then you do not need to run all your css files through the asp.net page processer.
<%@ Control %>
<style type="text/css>
div.content
{
background-image:(url(<%= Page.ResolveUrl("~/images/image.png") %>);
}
</style>
But the easiest way to solve the ~
problem is to not use a ~
at all. In Visual Studio, in Solution Explorer, right click your application, select Properties Window and change the Virtual Path to /
.
Inside of the .css file you can use relative paths; so in your example, say you put your css file in ~/Styles/mystyles.css. You can use url(../Images/Test.gif) as an example.
Make you life easy, just put images used in your CSS in the /css/
folder alongside /css/style.css
. Then when you reference your images, use relative paths (e.g. url(images/image.jpg)
).
I still keep images that are displayed with a <img>
in an /images/
folder. Photos for example are content, they are not part of the website's skin/theme. Thus, they do not belong in the /css/
folder.
In case you didn't know you could do this...
If you give a relative path to a resource in a CSS it's relative to the CSS file, not file including the CSS.
background-image: url(../images/test.gif);
So this might work for you.