Transformation equivalent for absolute position

I have an element with an unknown size with position = absolute, top = 1000, left = 1000.

Right now, the top left element of this element is at position (1000,1000), but I want the center of the element to be (1000,1000).

Is there a way to do this with CSS only?

+5
source share
1 answer

As stated in the comments , you can simply use transform: translate(-50%,-50%) 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 do not know the width / height of the element.

For instance:

 .element { background: #f00; width: 100px; height: 100px; transform: translate(-50%,-50%); position: absolute; top: 50%; left: 50%; } 
 <div class="element"></div> 

What are some alternative methods for vertical / horizontal centering?

+3
source

Source: https://habr.com/ru/post/1235840/


All Articles