Open In App

How to make an image center-aligned (vertically & horizontally) inside a bigger div using CSS ?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We will know how to center-align the image in a div tag using CSS & will also understand its implementation through the example. Given an image, we need to set the image that align to the center (vertically and horizontally) inside a bigger div. But first let’s create a basic structure, in which inside the body tag with id=outer there is an img tag and we will try to center the image within the outer div. We have given a border of 2px solid black to the outer div to recognize it easily.

HTML




<!DOCTYPE html>
<html>
   <head>
      <title>Horizontal and Vertical alignment</title>
      <style>
         #Outer {
         border: 2px solid black;
         height: 300px;
         }
      </style>
   </head>
   <body>
      <div id="Outer">
         <img src=
      </div>
   </body>
</html>


Examples of Centering the Image Vertically and Horizontally using CSS

1. Centering Image using position absolute and margin auto:

Example: This HTML code creates a webpage with an image inside a container div. The container div has a fixed height of 300 pixels and a black border. The image is positioned absolutely within the container, and the CSS properties set its margins to auto along with top, left, right, and bottom to 0, effectively centering the image both horizontally and vertically within the container.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Horizontal and Vertical alignment</title>
     
    <!-- Style to set horizontal and
        vertical alignment -->
    <style>
    #Outer {
        border: 2px solid black;
        height: 300px;
        position: relative;
    }
     
    img {
        position: absolute;
        margin: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }
    </style>
</head>
 
<body>
    <div id="Outer">
        <img src=
    </div>
</body>
 
</html>


Output:

2. Centering Image using background-position Property:

Example: This HTML code creates a webpage with a container div (#Outer) having a black border and a fixed height of 300 pixels. The background of the container is set to an image using CSS, which is centered both horizontally and vertically within the container using the `background property` with the `no-repeat` value and the `center center` position.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title> Horizontal and Vertical alignment </title>
    <style>
    #Outer {
        border: 2px solid black;
        height: 300px;
        background: url(
      background-position:center center;
    }
    </style>
</head>
 
<body>
    <div id="Outer"></div>
</body>
 
</html>


Output:

Centering Image using background-position Property



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads