CSS background-image


The CSS background-image property is used to set one or more background images for an element. The background image can be an image file (e.g., .jpg, .png) or a gradient.

selector {
  background-image: url('image.jpg');
} 
  • selector – The HTML element you want to style (e.g., div, body).
  • url('image.jpg') – The image file you want to set as the background. This can be a relative or absolute URL.

css-background-image


Example

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-image: url('background.jpg');
    }
  </style>
</head>
<body>

<h1>Welcome to My Website</h1>
<p>This page has a background image!</p>

</body>
</html> 

Using Multiple Background Images

You can use multiple images as backgrounds. Separate each image with a comma.

 

 div {
  background-image: url('image1.jpg'), url('image2.jpg');
  background-repeat: no-repeat, repeat;
}

notepad
  • The first image will be stacked on top, and the second one will be layered below.
  • You can control the position and repeat behavior of each background image.

Example

<!DOCTYPE html>
<html>
<head>
  <style>
    .header {
      height: 300px;
      background-image: url('header-bg.jpg'), linear-gradient(to right, rgba(255, 255, 255, 0.6), rgba(0, 0, 0, 0.6));
      background-size: cover, cover;
      background-position: center, center;
      color: white;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  </style>
</head>
<body>

<div class="header">
  <h1>My Header Section</h1>
</div>

</body>
</html> 

Background-Size & Position

You can control the size and position of the background image to make it fit or cover the element.

 

Background-Size:

  • cover – Ensures the image fully covers the element without stretching it.
  • contain – Makes sure the image is fully visible but may not cover the entire element.

Example

div {
  background-image: url('image.jpg');
  background-size: cover;
  background-position: center center;
} 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.