set an image as background using CSS

How to set an image as background using CSS?

Here is the following layout where we put an image (snow.jpg) as the background using CSS.

<div class="container">
    <h1>Hello World!</h1>
</div>
.container {
    border: 3px solid;
    padding: 20px;
    width: 500px;
    height:500px;
}

h1 {
    text-align: center;
}
a simple layout where we going to put an image as background

Set an image as background using CSS

The CSS background-image property is used to set an image as the background of the selected element.

Now, We have to use the url() function with the background-image property to define the path of the image.

background-image: url("/path/of/the/image.jpg");

In the following code, you can see there are few more CSS properties along with the background-image

  • background-color: – Always set the background color, because if for some reason the background image is not loaded, so that the user can read the text properly.
  • background-repeat: – Control the repetition of the background image.
  • background-size: – define the background image size.
  • background-position: – set the position of the background image.
.container {
  border: 3px solid;
  padding: 20px;
  width: 500px;
  height: 500px;


  background-color:#333333;
  background-image: url("./sonw.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}

h1 {
  text-align: center;
  color: white;
}
css image as background

Set the transparent color

h1 {
  text-align: center;
  color: white;
  /* Transparent background color */
  background-color: rgba(0, 0, 0, 0.6);
}
css background image with transparent color

CSS blend mode with the background image

The background-blend-mode is used to apply the blend mode to the background image.

.container {
    border: 3px solid;
    padding: 20px;
    width: 500px;
    height: 500px;
    background-image: url("./sonw.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;

    background-color: red;
    background-blend-mode: multiply;
}

h1 {
    text-align: center;
    color: white;
    background-color: rgba(0, 0, 0, 0.6);
}
CSS background image with blend mode