How to center absolutely positioned element in div using CSS ?

Sometimes we need to place an element into center absolute position relative to its nearest positioned ancestor in HTML to make it look more presentable. For centering an absolute positioned element in div we use the following examples:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <style>
        #content {
            position: absolute;
            left: 50%;
            transform: translateX(-50%)
        }
    </style>
</head>
  
<body>
    <div id="content">
        <img src=
    </div>
</body>
  
</html>

chevron_right


Output:

Explanation: Here, left is given 50% to place it in center horizontal. Transform is used to pull back the item with the half of its width to place it exactly in the center from the middle of the element. left: 50% is relative to the parent element while the translate transform is relative to the elements width/height.

Example 2:



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <style>
        .content {
            height: 400px;
            position: relative;
            border: 4px solid green;
        }
  
        .content img {
            margin: 0;
            position: absolute;
            top: 50%;
            left: 50%;
            -ms-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
        }
    </style>
</head>
  
<body>
    <p>
        Centering an abosulte positioned
        element inside a div both 
        horizontally and vertically
    </p>
      
    <div class="content">
        <img src=
    </div>
</body>
  
</html>

chevron_right


Output:

Explanation: Here left and top are given 50% to place it in the center horizontally and vertically. Transform is used to pull back the item with the half of its width to place it exactly in the center from the middle of the element. Therefore transform:translate is given -50% for both horizontal and vertical to adjust it centrally.

full-stack-img




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.