When working with position absolute divs, it can be tricky to center them, but it’s not impossible. In this blog post, we’ll go through the steps on how to center a position absolute div in CSS.
See the Pen Center position absolute div by Chethan S Poojary (@chethanspoojary) on CodePen.
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Step 1: Set the Position Property of the Parent Container
Before you can center a position absolute div, you need to set the position property of the parent container to relative. This is because the child div will be positioned relative to the parent.
.parent {
position: relative;
}
Step 2: Set the Position Property of the Child Div
Once you’ve set the position property of the parent container to relative, you need to set the position property of the child div to absolute. This removes the child div from the normal document flow and allows it to be positioned freely within its parent.
.child {
position: absolute;
}
Step 3: Position the Child Div
The next step is to position the child div within its parent container. To center the child div both horizontally and vertically, you can use the top and left properties in combination with transform and translate.
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Step 4: Add Additional Styling
Once you’ve centered the position absolute div, you can add additional styling as needed. For example, you can set the width and height properties to control the size of the div.
.child{
width: 100px;
height:100px;
background:skyblue;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%)
}
Centering a position absolute div in CSS requires just a few simple steps. By setting the position property of the parent container to a relative, the position property of the child div to absolute, and then using top, left, transform, and translate properties to position the child div, you can easily center it both horizontally and vertically within its parent container. With these steps in mind, you’ll be able to position your elements exactly where you want them on your web page.