Center an element that is position absolute
When you need to place an element in the center of another element, you first:
-
Position the parent element relative using:
position: relative
-
For the element that you want to center:
- Set the position to absolute, by using:
position: absolute
- Set the left and top properties to 50%, by using:
left: 50%; top: 50%
- Use the
transform
property to translate the element, by using:transform: translate(-50%, -50%)
- Set the position to absolute, by using:
Here is the snippet of code
.parent {
position: relative;
width: 350px;
height: 200px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Notes
The left: 50%
and top: 50%
declarations are relative to the parent, while the transform: translate(-50%, -50%)
is relative to the element width and height.
For a complete example, you can check the below snippet on CodePen:
Your JS is turned off. Please turn it on to see the CodePen. Here's a screenshot from the Pen
Try reload the page, our check out the pen on CodePen