• Angular
  • React
  • NextJs
  • Sass

How to Add Background Image in CSS

By Webrecto, August 19, 2023

The background-image property in CSS is used to add one or more background images in HTML elements. If we do not specify any background properties in the CSS code, the image is repeated and it covers the entire element. By default, the background image is positioned at the top-left corner of an element and repeated both horizontally as well as vertically.

Syntax:

background-image: url("");

In the HTML element, we use many types of images to set the background. The CSS code uses a graphic image like jpg, jpeg, png, gif, svg, and gradient to set the background of an element.

We can create 3 types of CSS to set the background image in the HTML element.

  • 1 - External css class
  • 2 - Internal css class
  • 3 - Inline css

Example:

1. Using external css class :

style.css
body {
    background-image: url("../images/lion.jpg");  
}
<!DOCTYPE html>
<html>
<head>
<title>webrecto</title>
<meta name="description" content="">
<link rel="stylesheet" href="css/style.css">
</head>
<body>

</body>
</html>

2. Using internal css class :

<!DOCTYPE html>
<html>
<head>
<title>webrecto</title>
<meta name="description" content="">
<link rel="stylesheet" href="css/style.css">
<style>
  body {
      background-image: url("images/lion.jpg");  
  }
</style>
</head>
<body>

</body>
</html>

3. Using inline css :

<!DOCTYPE html>
<html>
<head>
<title>webrecto</title>
<meta name="description" content="">
</head>
<body style="background-image: url(images/lion.jpg);">

</body>
</html>

Output:

How to Add Background Image in CSS