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

Given an image and the task is to set the image to align to center (vertically and horizontally) inside a bigger div. It can be done by using the position property of the element.

Example 1: This example uses position property to make the image align to center.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>                    

chevron_right


Output:

Example 2: This example uses center property to set the image to center in a div.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.