
How to Dead Center Absolutely Positioned Elements in CSS
Use transform: translate
with negative values of top
and left
to dead center an absolutely positioned element in CSS:
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
This will move the element -50%
to the top and also -50%
to the left. By default, anchor points are set to the top-left corner of an element. To dead center absolutely positioned elements, you need to move them back -50% on both axis. Think of it as setting an anchor point to the center.
Note that you should use the negative values of top
and left
. For different values, your translate
rule should look similar:
.center {
position: absolute;
top: 25%;
left: 30%;
transform: translate(-25%, -30%);
}
The first parameter of the translate
function is used for the x-axis, while the second is used for the y-axis.
Are you not using absolute positioning?
You can also use flexbox, to center an element, with only three lines:
.center {
display: flex;
justify-content: center;
align-items: center;
}
justify-content
centers it on the horizontal axisalign-items
centers it along the vertical axis
Another option is to set the line-height
to the height
of the container:
.center {
height: 250px;
line-height: 250px; /* Set the line-height to the same as the height */
}


Resources:

Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:
Courses

CSS - The Complete Guide (including Flexbox, Grid and Sass)

The HTML & CSS Bootcamp
