Have you ever upload a website and the image doesn't show up? Or the CSS doesn't work? Even though on your localhost everything is fine?
If that's the case you have come to the right article. So, let's get into it!
Before we dive into absolute and relative path, we need to know what is file paths.
According to W3Schools.
A file path describes the location of a file in a web site's folder structure.
Basically, it's the way of us as a developer to tell the browser where the file is located.
There are two types of file paths:
- Relative File Path
- Absolute File Path
First let's dive into the absolute path.
Absolute file path will always start from the root directory.
Let's say your working directory looks like this:
root/ index.html css/ style.css
To link the HTML file with the CSS file what you need to do is:
<link rel="stylesheet" href="/css/style.css">
It's the same as you write your
localhost URL on the browser:
By doing that, you can see your CSS code. So, think of absolute path as a full address to the file. It's always start from the root folder.
Now, let's explore the relative path.
Relative path will always start from the same directory of that file.
For example, let's say this is your folder structure.
root/ dist/ index.html css/ style.css
Now, if you're using absolute path to connect the
style.css, you can write:
<link rel="stylesheet" href="/dist/css/style.css">
While if you're using relative path, you can write it in a shorter way.
<link rel="stylesheet" href="./css/style.css">
For HTML, I would recommend to always you absolute path, since it's good for both user and developer and works well on offline.
But, for the rest use relative path (if possible).
Also, you might often notice something like this:
<link rel="stylesheet" href="css/style.css">
That's also relative path, but I don't recommend to do it that way. It isn't clear where is the starting point. The point is that you want to make it as obvious as possible where the starting point is.
Now, it's time for the challenge. It will make sure that you fully understand both absolute and relative path. Now bravely navigate to this GitHub repository and do the challenge. After you have completed the challenge, you can check my solution on the
solutions/ directory. Good Luck!
If you have done all the challenge, and then, 🎉 congratulation! 👍 You're amazing! I hope that now, you fully understand both absolute and relative path.
- Vandy Aditya Setia - 🛠️ Fixing Grammar Issue
- Devin Halim - 🛠️ Fixing Grammar Issue