File paths in HTML
File paths define the unique location of a file on the web. That file could be anything, for example an image, stylesheet, or another webpage.
There are two types of file path:
- Absolute
- Relative
Absolute file paths
An absolute file path includes the complete web address of the page to link to. This means they always point to the same place, regardless of the current directory.
If you’re linking to another website, you must use an absolute link.
<img src="https://www.lukeowen.co.uk/image.png" />
Relative file paths
A relative file path starts on the current webpage, and then looks for the file relative to the page.
Relative links are shorter, so they’re generally recommended when you’re linking to pages within your own site.
These examples all assume the starting page is: lukeowen.co.uk/blue/red
File is in the current directory
The most basic type of relative link is simply the file name. In this case the browser will just look in the directory of the current page.
If your entire website is in one directory, you’ll only ever need simple paths like this.
<!-- lukeowen.co.uk/blue/red/image.png -->
<img src="image.png" />
<img src="./image.png" />
File is in the root directory
A slash (/
) at the start of the file path tells the browser to start at the root (top) directory.
This is a pretty handy way for jumping straight to the top level, for example if you keep all your stylesheets in a css folder.
<!-- lukeowen.co.uk/image.png -->
<img src="/image.png" />
File is up one level
Two dots and a slash (../
) tell the browser to go up one directory level before following the rest of the file path.
<!-- lukeowen.co.uk/blue/image.png -->
<img src="../image.png" />
File is up multiple levels
By chaining dots and slashes you can go up as many levels as you need to. Though at some point it just gets silly.
<!-- lukeowen.co.uk/image.png -->
<img src="../../image.png" />