Slash (/) vs tilde slash (~/) in style sheet path

asp.netPathStylesheetRelative PathAbsolute Path

asp.net Problem Overview


ASP.NET offers two ways to specify paths for style sheets:

<link href="/common/black_theme/css/style.css" rel="stylesheet">   (this is working)
<link href="~/common/black_theme/css/style.css" rel="stylesheet">  (this is not working)
  • How are these paths resolved?
  • Why are the generated paths different?
  • Which one should I pick in which case?

As per my knowledge, ~ represents the root directory of the application. "common" is the folder below the website root (named testsite.demo) in IIS.

Physical path: D:\Physicalpath\WarpFirstSite\testsite.demo
"common" folder: D:\Physicalpath\WarpFirstSite\testsite.demo\common

asp.net Solutions


Solution 1 - asp.net

  • / - Site root
  • ~/ - Root directory of the application

The difference is that if you site is:

http://example.com

And you have an application myapp on:

http://example.com/mydir/myapp

/ will return the root of the site (http://example.com),

~/ will return the root of the application (http://example.com/mydir/).

Solution 2 - asp.net

The second won't work because its not a recognised path by anything except asp.net code on the server side. And since your link tag is regular html and not a server control it never gets processed.

Solution 3 - asp.net

If you add runat="server" in your link tag then it would works perfectly....

like this....

<link href="~/common/black_theme/css/style.css" rel="stylesheet" runat="server"> 

(this is also working)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyasa MadhaviView Question on Stackoverflow
Solution 1 - asp.netOdedView Answer on Stackoverflow
Solution 2 - asp.netCRiceView Answer on Stackoverflow
Solution 3 - asp.netGaurav AgrawalView Answer on Stackoverflow