How to center an absolutely positioned element inside its parent

Centering an element with absolute horizontal and vertical positioning is one of those things that seems simple, but sometimes gets tricky. Besides that, it’s something that we need to do very often for most of the layouts we implement.

Let’s assume our HTML code looks like this:

<div class="parent">
<div class="centered box">I'm completely centered!</div>
</div>

We will implement two CSS methods to solve our problem. The first one is for cases where your element has a fixed width and the second one is for cases where you don’t specify the width of your element.

Method 1

/* METHOD 1 */
.parent{
width:100vw;
height:100vh;
position: relative;
}
.centered{
text-align: center;
position: absolute;
top: 50%;
left: 0;
right: 0;
margin: auto;
transform: translateY(-50%);
}
.box{
width: 250px;
color: #fff;
padding: 20px 0;
border-radius: 4px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
background: linear-gradient(-30deg, #4A00E0, #8E2DE2);
}

First Method:

We use 'left:0', 'right:0', and 'margin:auto' to achieve horizontal centering. Then, in order to achieve vertical centering, we use 'top: 50%', which makes the element stay almost centered - this will only center the element according to its top boundary. To make it completely centered, we need to use 'transform: translateY(-50%)' to bring the element up by half of its height.

Method 2

/* METHOD 2 */
.parent{
width:100vw;
height:100vh;
position: relative;
}
.centered{
position: absolute;
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
}
.box{
text-align: center;
color: #fff;
padding: 20px;
border-radius: 4px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
background: linear-gradient(-30deg, #4A00E0, #8E2DE2);
}

Second Method:

In this method, we do the same thing to achieve vertical centering. To achieve horizontal centering, since we don’t have a fixed width,we basically have to do the same thing we did to get the vertical one, but with a different axis. We only specify 'left: 50%' and add another property to our transform: 'translateX(-50%)'.

Below is the final result for both methods: