How to Center Background Image in Div Tag With CSS

There is a vast usage of background images to make good looking websites.

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 Image 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 fix 200*200 PX div container with background class to contain 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 cover size for 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

I hope you understand how to center an image for fix size container 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 *

Read previous post:
armstrong number in c programming language
How to Check Amstrong Number in C Program

We are going to discuss here how to check the given number is either Armstrong number or not. What is...

Close