0

How can I align a div by its center?

So, what I'm asking for is basically cx and cy for the circle tag, but for div. Something like <div centerX="50px"> etc.

13th Sep 2019, 1:58 AM
Cheese Burger Joe
Cheese Burger Joe - avatar
2 ответов
+ 4
In javascript, you can use the element.getBoundingClientRect() method to get the element’s current left, right, top, bottom, width and height. If you add half of the width to the left value and half of the height to the top value you’ll have the absolute position of the center in pixels. Conversely, if you wanted to write a function to position a div by its center point, do this: function positionByCenter(x,y, elemID){ var element = document.getElementById(elemID); var rect = element.getBoundingClientRect(); element.style.left = x-(rect.width/2)+”px”; element.style.top = y-(rect.height/2)+”px”; } I hope this helps!
13th Sep 2019, 4:44 AM
Mike Perkowski
Mike Perkowski - avatar
0
If you have a div with elements inside, you can use the css property : Margin : 0 auto; This does not work on empty elements thou
13th Sep 2019, 11:00 AM
Dominique Abou Samah
Dominique Abou Samah - avatar