If you would like to hire my services, you can now do so by visiting the following link:
Website Design Darlington
Article Statistics
Code Bank Statistics
Summary: An example of how to reference files based on the root path of the application.
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 pathYou could hard code the full http path to this file so that it looks like: <link id="stMainLayout" rel="stylesheet" type="text/css" media="screen" href="http://aspnetlibrary.com/stylesheets/mainlayout.css" /> 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 pathYou can add a relative path so that the style sheet is referenced in relation to the current page e.g. <link id="stMainLayout" rel="stylesheet" type="text/css" media="screen" href="stylesheets/mainlayout.css" /> 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 SolutionOne 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. <link id="stMainLayout" rel="stylesheet" type="text/css" media="screen" runat="server" href="~/stylesheets/mainlayout.css" /> 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.
Posted on 28/08/2007 05:13:52
1. Joshua 16/06/2008 13:36:32
This doesn't work for me. I have the exact same line you do with runat="server" and it's not converting it for me. I'm using VS 2008 and doing this in a master page. Thanks!
2. Joshua 16/06/2008 13:39:21
Nevermind, I figured it out. You didn't mention that I needed to have the head command also set to runat="server" for this to work. After changing that it works perfect now. Thanks!
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.