I got an element with unknown size with position=absolute, top=1000, left=1000.
Right now, the top left of that element is at position (1000,1000) but I'd want the center of the element to be (1000,1000).
Is there a way to do that with CSS alone?
We can use CSS absolute positioning to overlap elements, but there's some advantages to using CSS grid instead.
Moving elements with translate() is better than absolute positioning (top, left, right, bottom) If you plan to make an animation by using position: absolute and set top, left, right or bottom please don't. Just use translate.
The transform origin is the point around which a transformation is applied. For example, the transform origin of the rotate() function is the center of rotation.
The default value of the transform origin is at 50% 50%, which is exactly the center of any given element. The transform-origin can be specified using offset keywords, length values, or percentage values.
As pointed out in the comments, you can simply use transform: translate(-50%,-50%)
in order to center the element vertically/horizontally. Fortunately, this method works for dynamic values, which means that it will work well in your case since you don't know the width/height of the element.
For example:
.element {
background: #f00;
width: 100px;
height: 100px;
transform: translate(-50%,-50%);
position: absolute;
top: 50%;
left: 50%;
}
<div class="element"></div>
For what it's worth, here are some alternative methods for vertical/horizontal centering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With