Search code examples
htmlhreffilepathsrc

how to properly link source in html inside folders?


i have multiple folders with other htmls, i want to link them all between each other.

folder structure looks like this:

Main Folder
   index.html
   nav.js
   Project Folder
      project1.html
      project2.html
   images
      image1.png
      image2.png
 

this is how i try to link:

  1. index.html: <a href="/Project Folder/project1.html"></a> <a href="./Project Folder/project1.html"></a>
  2. project1.html: <a href="/index.html"></a> <img src="./images/image1.png> <script src="./nav.js">

it works with visual code live, but doesn't work when i open just index.html. i get error for not loading neither image or script, and when i press on a i get another error of page not found.

i want to figure out what is proper way of linking items inside multiple folders and in which case i have to use "./" or "/" and if there is anything else.


Solution

  • When you start a URL with "/", it goes to the very beginning (root) of the path.

    When using VSCode Live Server, it runs a local server which has a root path of the directory you have open in VSCode. With live server, you will have a URL like localhost:5000/index.html. As the root path is in the same location where the index.html is located, you can just type /index.html to access it.

    When you manually open the index.html, the root directory changes to the root of the drive you have the file located in (e.g. C:). If you open the file manually, your web browser is opening something like C:/Users/User/Desktop/Website/index.html. If you were to try access /index.html, it would then go to C:/index.html on your hard drive.

    If you are trying to access a file that is in the same directory as the current html file you have open, you want to remove the / from the beginning of the URL.

    If you are wanting to access a file that is accessible from the parent directory, you want to have it start as ../

    To make what you currently have work when you directly open the .html file, make the following changes:

    index.html

    Before: <a href="/Project Folder/project1.html"></a>

    After: <a href="Project Folder/project1.html"></a>

    project1.html

    Before: <a href="/index.html"></a> <img src="./images/image1.png"> <script src="./nav.js">

    After: <a href="../index.html"></a> <img src="../images/image1.png"> <script src="../nav.js">