views:

269

answers:

2

What are the pros and cons of referencing web assets using relative or absolute paths? For example:

<link rel="StyleSheet" href="/css/mystylesheet.css" type="text/css" />
<img src="/images/myimage.gif" alt="My Image" />

vs.

<link rel="StyleSheet" href="../css/mystylesheet.css" type="text/css" />
<img src="../images/myimage.gif" alt="My Image" />
+1  A: 

The answer is "it depends". But most of the time, the absolute path is probably best.

I use absolute paths where I am using templating, or if I am using Apache's mod_rewrite.

You might use a relative path if you had a page with an accompanying stylesheet that might be placed at different levels when it gets uploaded. i.e. You've written a page that will be used on many website, and some people might upload it to the root directory and some people might not - by using a relative path, as long as they upload the html file and css file together, it will work - whereas an absolute path wouldn't in this scenario.

Sohnee
+1  A: 

It depends on your server side organization of the files. If you use URL rewriting or a front controller than relative paths probably won't work.

On the other hand, if you use absolute paths (and even if you just use "normal" HTML pages) you can rearrange the pages without caring about their location in your structure.

Felix Kling