Method 1: Using Local Directory Path
To set a background image that resides in the local directory, use the “background-image” property. When the image and HTML file are in the same folder. Then, pass the file name with its extension/format to the “url()” as a value:
The above snapshot shows that the image “book.jpg” and the HTML file “imgpath.html” are in the same folder.
So, the code for setting the background image is:
In the above code snippet:
- The “url()” function takes the image name as an argument and assigns it to the “background-image” property.
- Both “height” and “width” properties set the size of the “div” element to 400px and 300px, respectively.
- The “color” property controls the color of the text in that div.
After executing the above code snippet:
The output confirms that the image is placed successfully.
Accessing Images from Another Folder
Suppose the image is placed in another folder. To access the path of the selected image that is provided in the “URL()” function, follow below procedure:
In the above snapshot, the path of the image from the HTML file is displayed.
Below is the code snippet that accesses the image and set it as a background image:
After executing the above code, the output looks like this:
The output confirms that the image is placed in another folder and set as background.
Method 2: Using URL Image
To set the background image directly from the internet. Get the URL of the image by copying the address of the image from the web browser. Then, insert that address as a value to the “url()” function of the “background-image” property:
Other properties like height, width, padding, etc. work in the same manner as in the above method.
After executing the above code, the webpage looks like this:
The output confirms that the online image is placed as a background.
Conclusion
To set the background image path, use the image path relative to the HTML file or paste the URL of the online image as a value of the src attribute. If the image resides in the local directory, simply add the image path relative to the HTML file. In the second case, copy the exact path of the image and insert that path as an argument for the “url()” function of the “background-image” property.