Have you seen any websites without images? Yes, we still might get a few, but they are rare these days. Let’s learn how you can add images to HTML documents.
Modern web relies hugely on images relevant to the site content as this helps to improve the website appearance and helps readers to understand the content better.
A website can contain multiple images that are often organised in the subdirectories and folders. Thus, it’s important to learn, how you can include an image in an HTML file from a folder.
<img> HTML tag
You can include an image in HTML using the
<img> HTML tag.
img <src="flowers.jpg" alt="A Flower Bouquet"/>
<img> loads the image and places it on the web page. It has 2 important attributes:
- src - Specifies the source location where the browser will look for the image file. Once it gets the image file, it loads the image on the web page. We can use a URL (Uniform Resource Locator) to display an image from another website.
- alt - Specifies the text we need to display if the image is unavailable or if the system can’t load the image. This text also helps visitors with disabilities using a screen reader.
How to set the image source in HTML
Let’s learn a bit more about how you specify the source of the image.
The base case is to specify the filename of the image that you’d like to place in the HTML document.
<img src="flowers.jpg" alt="A Flower Bouquet"/>
The browser will look for the image in the same folder where you’ve placed the HTML document.
If the image is located in a folder or a subdirectory, you need to include it to the source as well.
<img src="/images/flowers.jpg" alt="A Flower Bouquet"/>
After you’ve added the
/images string to the source, the browser will look for the image
flowers.jpg in it instead of the current directory.
How to add an image to HTML from a remote location
The images that you use in your HTML pages don’t have to be located next to them. You can easily add images from remote locations (other websites or file storages) using a URL.
How to use “.” or “..” as the image source in HTML
You can instruct the browser to look for the image in the current directory using single dot
. in the
<img src= "./flowers.jpg" alt="A Flower Bouquet"/>
Or, if you want to move one directory up, you use two dots
.. to ask the browser to start looking for the image one level above the current directory.
<img src="../otherImages/flowers.jpg" alt="A Flower Bouquet"/>