Absolute and Relative Paths
How to write paths, aka URLs, in HTML and CSS. This article deals with both absolute and relative paths.
There are three types of paths, the first is the absolute path, this is usually used when linking to resources placed on other websites, outside of your domain.
There are two types of relative paths, both of which are used to link to internal resources on your domain. The first is called the root-relative, and the final type is the document-relative.
Of cause you won't always be linking from "documents", so a better description of document-relative paths, would be resource-relative, which reflect the todays web much better.
Root Relative Paths
These are Relative to the Root of your server, I.E. Linking from SubDir/Page2.html to Page.html in the same directory by the Root Relative Path:
/SubDir/Page.html
Is the equilivant of the Document Relative Path:
Page.html
Root Relative are very useful for websites using Mod Rewrite. Web developers new to mod-rewrite are likely to encounter the problem with broken URLs when using Document Relative Paths.
The root of the server may refer to htdocs, or the directory where you usually place the index.html I.E. http://www.brugbart.com/ThisIsTheRoot
Document Relative Paths
Note. These paths are known to break when you change the site structure, such as if you decide to enable Mod Rewrite later. therefor its recommended either to use Root Relative Paths, or Absolute Paths.
If you want to link to SubDir/Page.html from index.html in the root by using the Document Relative way, you would do like below:
SubDir/Page.html
Linking from SubDir/Page.html to a page in the root would require the following path:
../PageInRoot.html
The "../" in front of the page name, basicly says go up one. If you need to go up more then one time, IE. When having more SubDirectories, simply add more dots as needed. The below will go up 3 times, I.E. From SubDir/SubDir/SubDir/Page.html
../../../PageInRoot.html
Absolute Paths
Absolute Paths are entered as follows:
http://www.brugbart.com/SubDir/Page.html
Absolute vs Relative URLs
Using Root Relative Paths for internal resources (images, css files, etc), will fix most broken URLs introduced by server "friendly URL" systems. They are also a good choice if your aim is to lower the file-sizes of your pages, and decrease load times.
Generally you would want to use root-relative URLs. But if you are using subdomains, then you don't have much choice, other then to use the absolute URLs.
Examples
To understand this Article, you may use the below as your reference. The below Examples shows how to enter the URL for an image located in the same directory as the .html file.
Document Relative Example
<p><img src="MyImage.jpg" alt="An Image"></p>
Root Relative Example
<p><img src="/SubDir/MyImage.jpg" alt="An Image"></p>
Absolute Example
<p><img src="http://brugbart.com/SubDir/MyImage.jpg" alt="An Image"></p>