HTML Background Images: A background image can be indicated for almost any HTML element.
In HTML, background images are set using CSS. CSS allows you to set a background image for any HTML element. Also you can indicate its position, whether it should repeat across the page, how it should repeat and so on.
In this article, you will learn-
Background Image on a HTML element.
To add a background image on an HTML element, use the HTML style attribute and the CSS background-image property:
Example
Add a background image on a HTML element:
<div style="background-image: url('img_girl.jpg');">
You can likewise indicate the background image in the <style> element, in the <head> segment:
Example
Determine the background image in the <style> element:
<style> div { background-image: url('img_girl.jpg'); } </style>
Background Image on a Page
In the event that you need the whole page to have a background image, you should indicate the background image on the <body> element:
Example
Add a background image for the whole page:
<style> body { background-image: url('img_girl.jpg'); } </style>
Background Repeat
On the off chance that the background image is smaller than the element, the image will repeat itself, horizontally and vertically, until it arrives at the finish of the element:
Example
<style> body { background-image: url('example_img_girl.jpg'); } </style>
To stay away from the background image from repeating itself, set the background-repeat property to no-repeat.
Example
<style> body { background-image: url('example_img_girl.jpg'); background-repeat: no-repeat; } </style>
Background Cover
On the off chance that you need the background image to cover the whole element, you can set the background-size property to cover.
Additionally, to ensure the whole element is constantly covered, set the background-attachment property to fixed:
Along these lines, the background image will cover the whole element, with no stretching (the image will keep its original proportions):
Example:
<style> body { background-image: url('img_girl.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } </style>
Background Stretch
On the off chance that you need the background image to stretch to fit the whole element, you can set the background-size property to 100% 100%:
Try resizing the browser window, and you will see that the image will stretch, yet consistently cover the whole element.
Example
<style> body { background-image: url('img_girl.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: 100% 100%; } </style>
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.