How to center an element with position absolute

  1. Set the parent element to position: relative;
  2. Set the child (element to center) to position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);

Here's the formatted CSS:

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

The way position: absolute works, is that it places the element in relation to the nearest parent element that has position: relative;. To control your positioning precisely, you'll probably want an immediate parent or wrapper div with position set to relative. You can put position: relative on a parent further up the DOM tree if needed, though. For example, to center a modal or popup, you might want position: relative on the <body> or <html> tag.

Full example

The UI - two divs:

parent and child div uncentered

Screenshot of my HTML and CSS:

HTML for the parent and child div uncentered

The result after centering with position: absolute:

parent and child div centered

The CSS with position: relative and position: absolute:

CSS changes to center child div

You can play around with the percentages on the child element. Maybe you want the child to be at the very bottom of the parent. You could adjust the top % or use another unit like pixels. You could also use the bottom property instead of top. The translate percentages can also help you position more precisely.


These changes here will put the child centered at the very bottom:

CSS for centering child at the bottom

And what it looks like:

The child element centered at the bottom of the parent.