How to Center Background Images in Div Tag With CSS

Many times designers face an issue with centering background images using CSS. Here we will discuss how to center background images using CSS.

Read Also: Onhover Effect With Inline CSS and JavaScript

Centering Background Images Using CSS

Many times we face a problem to fit different size images in a fixed size container. In the fixed-size container, it is hard to manage background image; an image may overlap, cut, or may overflow.

To solve that problem, here we are going to learn how to center a background image in a div element with CSS. This method contains the usage of background-size and background-position to center background image in CSS.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Center Background Images Using CSS - Errorsea</title>
      <style>
         .background{
         height: 200px;
         background-image: url(YOUR_IMAGE_PATH);
         width: 200px;
         display: block;
         background-position: center;
         background-size: cover;
         }
      </style>
   </head>
   <body>
      <div class="background"></div>
   </body>
</html>

Explanation

  • First, we create a fixed 200*200 PX div container with background class to contain the background image.
  • Then, we set a background image with a background-image property.
  • After that, we position the image center with a background-position property.
  • Finally, we set the cover size to best fit the image in a container with the background-size property.

Note: Change image path in background-image property.

Read Also: Bootstrap Vertical Align

Conclusion

I hope you understand how to center an image for fixed-size containers with background property. You can copy the above code and test it your self.

Enjoy Designing πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *