Open In App

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

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

When designing web pages, achieving proper centering of elements is crucial for aesthetics and user experience. In this guide, we’ll explore techniques to center an absolutely positioned element within a <div> container. Whether you’re creating a landing page, a form, or any other web component, understanding these methods will enhance your design skills.

Let’s first create a simple HTML structure with a div container along with an image inside it. Then we will give some styling.

HTML




<!DOCTYPE html>
<html>
 
<head>
</head>
 
<body>
    <div id="content">
        <img src=
    </div>
</body>
</html>


Examples of Centering Absolutely Positioned Elements Using CSS

1. Centering Div horizontally with Position absolute Property:

This example demonstrates the centering of an absolute positioned element using the <div> tag.

HTML




<!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, the left is given 50% to place in the center horizontally. Transform is used to pull back the item with 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 element’s width/height.

2. Centering Div horizontally and vertically with Position absolute Property:

This example demonstrates the centering of the absolutely positioned element in horizontal & vertical directions in the <div> tag.

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=
    </div>
</body>
 
</html>


Output: 

Explanation:

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

 



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

Similar Reads