In many cases, elements or controls on your page must refer to an external resource such as an image or another *.aspx file. To refer to these resources I prefer to use relative paths, because on my development machine the URL might be http//:localhost but on the production machine the URL might have a host header, like http://mywebapp.roelvanlisdonk.nl. or an other port like http://localhost:81.

When using relative paths there are two kinds of elements

  • Not web server controls like (html tags, css statements etc.)
  • Web server controls (ASP .NET server controls)

Not web server controls (html tags, css statements etc.)

Always start an URL with a "/", no matter where you are in the tree structure, this relative URL will always work

  • "/Images/Logo.png"
  • <img alt="Logo" src="/Images/Logo.png" />

Don’t use:

  • "../" like "../Images/Logo.png"
  • "no slash at all" like "Images/Logo.png"


Web server controls

Always start an URL with a "~/"

  • "~/Images/Logo.png"
  • Response.Redirect("~/Pages/MyPage.aspx");
  • <asp:HyperLink ID="HyperLink1" runat="server" navigateUrl="~/Pages/Default.aspx">Test HyperLink</asp:HyperLink>

Don’t use:

  • "/" like "/Images/Logo.png"
  • "../" like "../Images/Logo.png"
  • "no slash at all" like "Images/Logo.png"


See: http://msdn.microsoft.com/en-us/library/ms178116.aspx

One Reply to “Best practices for using relative paths in CSS, HTML and ASP .NET”

  1. Hi and thanks! 🙂

    One Q: how would you recommend storing and using paths to images in html? I have a default image that I use in many places in my web application like
    If this image is used with this hardcoded path in the html, would we not want to store this path somewhere in a constants-like file? So that when a designer comes along he doesn’t need to search the whole solution for usages of “/Images/Default.jpg”, he could just edit it in one place….

    Appreciate your input, thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts