Reference app relative virtual paths in .css file

后端 未结 8 2008
生来不讨喜
生来不讨喜 2020-12-24 02:03

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

相关标签:
8条回答
  • 2020-12-24 02:47

    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.

    0 讨论(0)
  • 2020-12-24 02:50

    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") %>);
    
    0 讨论(0)
  • 2020-12-24 02:53

    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 /.

    0 讨论(0)
  • 2020-12-24 02:54

    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.

    0 讨论(0)
  • 2020-12-24 02:56

    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.

    0 讨论(0)
  • 2020-12-24 03:04

    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.

    0 讨论(0)
提交回复
热议问题