Skip to content
Related Articles

Related Articles

How to center absolutely positioned element in div using CSS ?
  • Last Updated : 05 Jun, 2020

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:




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

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:




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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :