Open In App

How to center the absolutely positioned element in div using CSS?

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Centering an absolutely positioned element in a div using CSS involves adjusting the position both vertically and horizontally. By using a combination of the top, left, and transform properties, we can ensure the element is perfectly centered within its container. This method creates a balanced and visually appealing layout on the page.

Using top, left, and transform Properties

This approach centers an absolutely positioned element by setting top: 50% and left: 50%, which moves the element’s top-left corner to the center of the container. To fully center the element itself, we apply transform: translate(-50%, -50%), which shifts the element back by half its width and height for perfect centering.

Syntax

.element {    position: absolute;   
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

Example: In this example, the image is centered inside the outer div using top: 50%, left: 50%, and transform: translate(-50%, -50%). The outer div has position: relative, which allows the image to be perfectly centered both horizontally and vertically.

HTML
<!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 absolute positioned element inside a div both horizontally and vertically </p>
        <div class="content">
            <img src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"/>
        </div>
    </body>
</html>

Output: 

Centering Div horizontally and vertically  output


Note: This method has some drawbacks. The absolutely positioned element needs to be carefully placed to stay inside the container or browser window and avoid overlapping with other elements.

Also, if the container’s size changes, the element might not stay perfectly centered.



Next Article

Similar Reads