21. HTML File Paths
What you will learn
- What a file path is
- The difference between relative and absolute paths
- How to use
../to go up a folder - How to organise a small website’s files
What is a file path?
A file path tells the browser where to find a file, such as an image, a stylesheet, or another page. You use paths in attributes like src and href.
An example folder structure
Imagine your website folder looks like this:
Folder structure
my-site/
index.html
about.html
css/
style.css
images/
logo.png
pages/
contact.html
Path types
| Path | Meaning |
|---|---|
logo.png |
A file in the same folder as the current page |
images/logo.png |
A file inside a sub-folder |
../images/logo.png |
Go up one folder, then into images |
/images/logo.png |
Start from the root of the website |
https://example.com/logo.png |
A full address on another website (absolute) |
Examples from index.html
Example (inside index.html)
<img src="images/logo.png" alt="Site logo">
<link rel="stylesheet" href="css/style.css">
<a href="about.html">About</a>
<a href="pages/contact.html">Contact</a>
Examples from pages/contact.html
This file sits one folder down, so it must climb up with ../ to reach the others.
Example (inside pages/contact.html)
<img src="../images/logo.png" alt="Site logo">
<link rel="stylesheet" href="../css/style.css">
<a href="../index.html">Home</a>
Relative or root-relative?
- Relative paths (
images/logo.png) depend on where the current page is. They work when you open files straight from your computer. - Root-relative paths (
/images/logo.png) always start at the top of the site. They need a web server, and they may fail if you open the file directly from your computer.
When you are learning and opening files from your computer, use relative paths. Root-relative paths are common on live websites.
File name tips
- Use lowercase letters, numbers, and hyphens:
my-photo.jpg. - Avoid spaces and special characters.
- Remember that many servers treat
Logo.pngandlogo.pngas different files. - Include the file extension:
.html,.png,.css.
Common mistakes
- Wrong capital letters in a file name.
- Forgetting
../when the page is inside a sub-folder. - Spaces in file names, which turn into
%20and cause confusion. - Hidden file extensions on Windows, so the real name is
logo.png.png.
Exercise
Using the folder structure above, write the src for the logo image when it is used inside pages/contact.html.
Show solution
<img src="../images/logo.png" alt="Site logo">
Knowledge check
1. What does ../ mean?
Go up one folder.
2. Which path style works best when opening files directly from your computer?
Relative paths.
3. Why avoid spaces in file names?
They get encoded as %20 and cause errors.
Summary
- A path tells the browser where a file is.
- Use
../to go up a folder. - Keep file names lowercase, with no spaces.