How to Center a Background Image Inside a Div

In this snippet, you’ll learn how to center a background image within a <div> element. Of course, you need CSS properties. In particular, this is possible to do with the help of the background and background-size properties. Below you can see how these properties are used to achieve our goal.

Solutions with the CSS background and background-size properties

In our example below, we use a <div> element and give it a class attribute, then style the class in the CSS section. You need to specify the position of the image through the "center" value of the background shorthand property. Set the width of your image to "100%". In this example, we also specify the height and background-size of our image.

Example of centering the background image within a <div> with the background property:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
   <style>
     .bg-image {
       width: 100%;
       height: 200px;
       background: url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg") no-repeat center;
       background-size: 250px;
     }
   </style>
 </head>
 <body>
   <div class="bg-image"></div>
 </body>
</html>

Result

If you want to center your background image inside a <div> element and display the whole image without any of its part being clipped or stretched, try the following example, where we set the background-size property to its "contain" value.

Example of centering the background image with the "contain" value of the background-size property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .bg-image {
        height: 400px;
        background: url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg") no-repeat center;
        background-size: contain;
      }
    </style>
  </head>
  <body>
    <div class="bg-image"></div>
  </body>
</html>

Our last example demonstrates how you can fill your entire <div> element with the background image and leave no extra space. You only need to use the “cover” value of the background-size property.

Example of centering the background image with the "cover" value of the background-size property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .bg-image {
        width: 100%;
        height: 400px;
        background: url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg") no-repeat center;
        background-size: cover;
      }
    </style>
  </head>
  <body>
    <div class="bg-image">
      This is some example.
    </div>
  </body>
</html>