by Sai gowtham

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");
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2022 (Beginner + Advanced)
JavaScript - The Complete Guide 2022 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY