How to center an element with position absolute
- Set the parent element to
position: relative;
- 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:

Screenshot of my HTML and CSS:

The result after centering with position: absolute
:

The CSS with position: relative
and position: absolute
:

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:

And what it looks like:
