Search code examples
htmlpathrelative-pathabsolute-path

Should image/css/javascript references from HTML use relative or absolute paths?


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" />

Solution

  • 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.