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.
2 Answers
+ 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!
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