One of the most common reasons beginners pull their hair out when learning HTML is because their images won't load, or their CSS styles refuse to apply. 99% of the time, this happens because the file path is written incorrectly.
A file path describes exactly where a file sits within a web server's folder structure. There are two distinct types of file paths you must understand: Absolute paths and Relative paths.
An absolute file path is the full, complete web address (URL) pointing to a specific file anywhere on the internet. It starts with https:// or http://.
You use absolute paths when you are linking to a file hosted on a completely different website than your own.
<!-- Using an absolute path to load an image from Wikipedia -->
<img src="https://upload.wikimedia.org/wikipedia/commons/logo.jpg" alt="Logo">
<!-- Using an absolute path to link out to Google -->
<a href="https://www.google.com">Go to Google</a>
A relative file path points to a file relative to the current page you are working on. You use relative paths when linking to files hosted on your own server.
This is crucial because if you build your site on your local computer (`C:/User/Desktop/Site`) and then move it to a real web server (`https://mysite.com`), relative paths will automatically adapt and continue to work without breaking!
To write a relative path, you must understand your folder tree. Imagine this is your website's folder structure:
Let's pretend we are currently coding inside the main index.html file from the structure above. Here are the 4 main ways to navigate the folders using relative paths:
| Path Format | What it does | Example Code |
|---|---|---|
filename.ext(No slashes) |
Looks for the file in the exact same folder as the current page. | <a href="contact.html"> |
folder/filename.ext(No leading slash) |
Looks down into a sub-folder located in the current folder. | <img src="images/logo.jpg"> |
/filename.ext(Starts with a slash) |
Immediately jumps to the absolute root base of the entire website domain. | <a href="/contact.html"> |
../filename.ext(Dot Dot Slash) |
Jumps up one parent folder. (Crucial for exiting a sub-folder like `pages/about.html` to reach the root). | <a href="../index.html"> |
../ command multiple times to climb up multiple nested folders. For example: <img src="../../images/logo.jpg"> will jump up two folders before looking for the "images" directory.