How to set a Background image in Html
In this tutorial, we are going to learn about how to set a background image in html using css.
Setting background image in HTML
To set a background on any html element, we need to use the background-image
css property with a value
url(image-path)
.
Example:
<div class="container">
<h1>Hello everyone</h1>
</div>
.container{
background-image: url("car.png");
}
Note: The image should be saved in your website folder.
Similarly, you can also use the style
attribute to set a background image on an html element.
<div style="background-image: url('car.png');">
<h1>Hello everyone</h1>
</div>
Fixing the image repeat
If the background image size is smaller than the html element, then the image will repeat horizontally and vertically to cover the entire element size.
To fix this, you need to set a background-repeat
css property to no-repeat
.
.container{
background-image: url("car.png");
background-repeat: no-repeat;
}
Stretching the image
If you want to stretch the background image to fit the entire html element (width, height), you need to use the background-size
css property with a value 100% 100%
.
.container{
background-image: url("car.png");
background-repeat: no-repeat;
background-size: 100% 100%; /* width height */
}
Codepen demo
Setting background to the entire webpage
If you want to set a background image to an entire web page instead of a particular html element, you need to add a background-image
css property on the body
tag.
body {
background-image: url("car.png");
}