Learn to Code: Episode 011 – Using Relative Path – Intro to HTML Part 8 (last part)

Finally, this is the last part of the Introduction to HTML series. I’ve never thought it will reach 8 parts, but I think it’s important for absolute beginners to take things slow at first in order to get familiar with programming syntax, structure, and how to use a specialized text editor.

Now let’s talk about relative path. So far all images are in the same folder as the html files. But what if those images are inside another directory, for example, images folder? Let’s see what would happen. Let’s move both images to the images folder.

Since we are using the Live Server extension, moving files around will refresh the web page automatically. The image of banana and oranges are now gone and was replaced by the alternative text (alt) attribute.

To fix this, we just need to update the src attribute of the <img> element to include the "images/" prefix. That means that to get to the correct image, to browser needs to go to the images folder first. Once we do the update, Live Server will automatically reload the page and the images will be displayed once again. We can also add an extra "/" in the front or even a "./" and it will still work.

But what if the images folder is inside another folder? Let’s say, the assets folder? We just need to update the src attribute to include the assets/ prefix. Using ./assets/images/bananas.jpg would also work. The "." means the current directory.

<img src="./assets/images/bananas.jpg" alt="Picture of bananas">

What if the html is inside another folder instead? Let’s move the image files back to the root folder of our project and create an src folder and move the html file inside. Once again, the images will not be displayed. To fix this, we would need to “go up” another folder by using "../bananas.jpg". The double dot (..) means the parent directory of the current directory (.).

<img src="../bananas.jpg" alt="Picture of bananas">

Using the combination of .. and /, we can move around our directory structure to be able to find the correct file in our HTML document.

To recap:

. means the current directory/folder
.. means the parent directory/folder

Here is the full video:

Leave a Reply

Your email address will not be published. Required fields are marked *