Hire my services

If you would like to hire my services, you can now do so by visiting the following link:

Website Design Darlington

Article Statistics

ArticlesLatest Entry
2121-May-2008

Code Bank Statistics

CategoryTipsLatest Entry
Applications420-Feb-2008
Cache118-Apr-2007
Controls926-Jul-2007
CSS107-Sep-2007
Database428-Aug-2007
Dates128-Aug-2007
Email105-Mar-2007
Files123-Apr-2007
HTML101-Mar-2007
Images226-Mar-2007
Pages115-Oct-2007
Sessions122-Nov-2007
SQL Server1518-Mar-2008
Strings309-May-2007
Skip Navigation LinksHome > Articles > Reference files with relative paths

Reference files with relative paths

Summary: An example of how to reference files based on the root path of the application.Socialize it

If you have a Master Page that references a style sheet, you have a couple of options on how to add the href attribute that references files such as javascript or css documents. Some of these options include:

1) Use an absolute path

You could hard code the full http path to this file so that it looks like:

However, the problem with this is that it doesn't work on your development machine as the path will most likely point to your localhost.

2) Use a relative path

You can add a relative path so that the style sheet is referenced in relation to the current page e.g.

The problem with this method comes when you want to use the same Master Page for content pages that are placed in different folders within your application. As the path is relative to your content page and not the Master Page, pages which reside in a different directory will not be able to reference the correct path.


The Solution

One method I use is to make the link to the stylesheet into a server side accessible control by adding the runat="server" tag e.g.

By doing this, you can use the tilde sign (~) at the beginning of the href attribute which will return the root directory each time, regardless of where the content page is located. This means that you won't have to switch url's when deploying to live.

This method can also be applied to any element, not just a stylesheet or javascript file.

Reader Comments

1. Joshua 16/06/2008 13:36:32

2. Joshua 16/06/2008 13:39:21

Add your comments

Please keep your comments relevant to this page. Any inappropriate or purely promotional comments may be removed. Email addresses are never displayed but are required so you can confirm your comments.

Your Name:
 
Your Email:
 
Add your comments: